AES encryption on Java side - decryption on PHP side and selecting a single key

这一生的挚爱 提交于 2019-12-03 21:55:23

There seem to be a few things you are doing wrong, I'll go over these in order:

Always specify "Algorithm/Mode/Padding" when creating an instance of Cipher in Java. Otherwise you never know which mode and padding will be used, which is especially problematic if you want to pass encrypted data between different platforms and programming languages, since they will probably have different defaults. (for example Java's default padding is PKCS1Padding where as PHP's mcrypt_decrypt() requires ZeroBytePadding)
So initialize ALGO with:

/* ZeroBytePadding should better not be used in practice */
private static final String ALGO = "AES/CBC/ZeroBytePadding";

As Roland Jansen has already mentioned, is the Java AES the 128-bit version. So use in PHP:

MCRYPT_RIJNDAEL_128

Third, you must always specify a different random IV for every encryption (must not be secret). You then must use the same IV for decryption. So you will also have to generate an IV in java that you then pass to PHP and use for decryption there.

byte[] iv = new byte[16]; // must be 16 bytes for AES-128
new SecureRandom().nextBytes(iv); // generate random bytes
IvParameterSpec ivSpec = new IvParameterSpec(iv);

/* create instance of Cipher and keys */

cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);

As of now you also generate a random IV in PHP, which will obviously not lead to the desired plaintext. So do the following in php for decryption:

 $key = "{insert Java encryption key here}";
 $iv; = "{insert Java encryption IV here}";

 mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $ciphertext, MCRYPT_MODE_CBC, $iv);

If it still does not work after these fixes, the problem is probably the encoding of the ciphertext- or the key/IV-Strings. Try to make sure that you pass exactly the same data to PHP which you receive from cipher.doFinal in Java then.

I hope, I could help you.

This link http://www.androidsnippets.com/encrypt-decrypt-between-android-and-php has a tutorial to help you. If you want change the SecretKey.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!