Android – InvalidKeyException: Key length not 128/192/256 bits

androidencryptionexceptionimage

I'm trying to decrypt an encrypted image in Android using this code:

public class SimpleCryptoActivity extends Activity {
    private static final int IO_BUFFER_SIZE = 4 * 1024;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        try {
            AssetManager am = this.getAssets();
            // get the encrypted image from assets folder
            InputStream is = am.open("2000_1.jpg_encrypted");

            ByteArrayOutputStream baos = new ByteArrayOutputStream();  
            byte[] b = new byte[IO_BUFFER_SIZE];  

            int read;
            //convert inputstream to bytearrayoutputstream
            while ((read = is.read(b)) != -1) {  
                baos.write(b, 0, read);
            }   
            byte[] key = "MARTIN_123_MARTIN_123".getBytes("UTF-8");
            byte[] iv = "1234567890123456".getBytes("UTF-8");

            long start = System.currentTimeMillis()/1000L; // start
            byte[] decryptedData = decrypt(key, iv, b);

            //END
            long end = System.currentTimeMillis()/1000L;    // end
            Log.d("TEST","Time start "+ String.valueOf(start));
            Log.d("TEST","Time end "+ String.valueOf(end));

            //decoding bytearrayoutputstream to bitmap
            Bitmap bitmap = 
                BitmapFactory.decodeByteArray(decryptedData,
                                              0,
                                              decryptedData.length);    

            int i = bitmap.getRowBytes() * bitmap.getHeight() ;

            TextView txt = (TextView) findViewById(R.id.text);
            txt.setText(String.valueOf(i));
            is.close(); // close the inputstream
            baos.close(); // close the bytearrayoutputstream
        } catch (Exception e) {
            e.fillInStackTrace();
            Log.e("error","err",e);
        }
    } 

    //decrypt
    private byte[] decrypt(byte[] raw, byte[] iv, byte[] encrypted)
            throws Exception {

        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec ivspec = new IvParameterSpec(iv);         
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivspec);
        byte[] decrypted = cipher.doFinal(encrypted);

        return decrypted;
    }
}

and the exception is:

07-27 09:01:53.162: ERROR/error(3104): err
07-27 09:01:53.162: ERROR/error(3104): java.security.InvalidKeyException: Key length not 128/192/256 bits.
07-27 09:01:53.162: ERROR/error(3104):     at com.cryptooo.lol.SimpleCryptoActivity.onCreate(SimpleCryptoActivity.java:62)
07-27 09:01:53.162: ERROR/error(3104):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-27 09:01:53.162: ERROR/error(3104):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
07-27 09:01:53.162: ERROR/error(3104):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
07-27 09:01:53.162: ERROR/error(3104):     at android.app.ActivityThread.access$2200(ActivityThread.java:119)
07-27 09:01:53.162: ERROR/error(3104):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
07-27 09:01:53.162: ERROR/error(3104):     at android.os.Handler.dispatchMessage(Handler.java:99)
07-27 09:01:53.162: ERROR/error(3104):     at android.os.Looper.loop(Looper.java:123)
07-27 09:01:53.162: ERROR/error(3104):     at android.app.ActivityThread.main(ActivityThread.java:4363)
07-27 09:01:53.162: ERROR/error(3104):     at java.lang.reflect.Method.invokeNative(Native Method)
07-27 09:01:53.162: ERROR/error(3104):     at java.lang.reflect.Method.invoke(Method.java:521)
07-27 09:01:53.162: ERROR/error(3104):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
07-27 09:01:53.162: ERROR/error(3104):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
07-27 09:01:53.162: ERROR/error(3104):     at dalvik.system.NativeStart.main(Native Method)

Any suggestions how to fix that?

PHP code:

$files = array(
        '007FRAMESUPERIOR.jpg',
        '2000_1.jpg',
        'APLICACIONdescargaliga.jpg',
        'APPCOMMENTS.pdf',
        'AUDIOVISUALFOTO02.jpg'
        );
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
        $iv = "1234567890123456";
        $key = "MARTIN_123_MARTIN_123";
foreach($files as $file)
{
            $input_file = $folder . $file;
$text = file_get_contents($input_file);
            //$text = "Meet me at 11 o'clock behind the monument.";
            echo strlen($text) . "\n";
function addpadding($string, $blocksize = 16){
    $len = strlen($string);
    $pad = $blocksize - ($len % $blocksize);
    $string .= str_repeat(chr($pad), $pad);
    return $string;
}


$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, addpadding($text), MCRYPT_MODE_CBC, $iv);

Best Answer

As Alex already mentioned, Password-Based Encryption is the way to go for you. AES keys need to be exactly 128, 192 or 256 bits long. So passwords of arbitrary length won't work in your situation right away, but using a "normal" password of the right size is also wrong, because these kinds of passwords do not contain enough entropy and will allow attackers to brute-force them more easily because they are not random enough.


With that said, let's take a look at your implementation. Instead of taking a String as a password in PHP what you should probably do is generate 16 bytes (128 bit) with Java's `SecureRandom' class or anything equivalent in PHP (don't know if such a thing is available, remember it needs to be a cryptographically secure random number). Encode that using Base64 so that you obtain a String representation of the key to be used both in Java and PHP.

Do the same for an IV that is exactly 16 bytes long (always the same as AES block size), encode it to Base64 again. You do this not for the reason that it has to be secret or complicated, but for the encoding issues that your approach is almost surely to cause. As far as I know PHP's default encoding is not UTF-8, so your approach is doomed to fail.

Using these two values (Base64-decode them before usage!) you're ready to go on the PHP side. In Java, obtain your Cipher using

Cipher c = Cipher.getInstance("AES/CBC/PKCS5PAdding");

and initialize it with the same IV and key used in PHP (again remember to Base64-decode first).

Final note: I do not recommend what I just described because it means that your keys will be hardcoded into your source files. That is actually not really secure and generally frowned upon. If you want to do symmetric encryption with passwords, then you should use PBE and not store the passwords anywhere, at the very least not in the client code. Another possibility is involving asymmetric public/private key cryptography, e.g. using a Diffie-Hellman key exchange.