Question

I've got this code to decrypt a php (mcrypt) token.

The problem is, that the decode method always uses Rijndael-128 not -256. When I encode on the php side with -128, I can decode in Android. When using 256 its not working. (getHash returns a SHA-256 hashed key):

    String key = "987654321";
    SecretKeySpec keyspec = new SecretKeySpec(getHash(key), "AES");
    Cipher cipherDecode = Cipher.getInstance("AES/ECB/ZeroBytePadding");
    byte[] text = Base64.decode(
            "wdRe00YxTFGQ65QmWukPxFLlZRSPqmRY8tHufikBHW0=",
            Base64.DEFAULT);
    cipherDecode.init(Cipher.DECRYPT_MODE, keyspec);

    final byte[] decrypted = cipherDecode.doFinal(text);

    String decyptedText = new String(decrypted);

This should give the Text 'wdRe00YxTFGQ65QmWukPxFLlZRSPqmRY8tHufikBHW0=', but it doesn't.

How can I specifiy or force the correct code to be used?

Was it helpful?

Solution

Your issue is (probably) that you are using MCRYPT_RIJNDAEL_256. This is not equal to AES-256. MCRYPT_RIJNDAEL_256 specifies a block size for the Rijndael cipher of 256 bits. AES-256 on the other hand specifies a key size for the AES cipher of 256 bits. Rijndael with a block size of 128 bits was accepted by NIST to be the AES algorithm.

Probably it is best to keep to MCRYPT_RIJNDAEL_128 as MCRYPT_RIJNDAEL_256 does not specify a standardized cipher. You can still use AES-128, AES-192 or AES-256 by using 16, 24 or 32 keys (respectively). Be warned that PHP mcrypt does allow other key sizes (by adding zero valued bytes) and does not use any form of standardized padding. "ZeroBytePadding" is not compatible with PHP, as it adds a block of zero's if the plaintext is a multiple of the block size. PHP however does not add a block of zero's in that case.

If you do want to keep to a block size of 256 (but why should you) check out this answer.

OTHER TIPS

You may use JNCryptor:

JNCryptor myJNCryptor=new AES256JNCryptor();
byte[] ciphertext=cryptor.encryptData(yourtext.getBytes(), KEY.toCharArray());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top