Encryption using AES-128 in Java

十年热恋 提交于 2019-12-03 00:51:21

The problem isn't with the IV or the padding as I initially thought. It is with how you are handling the key in the PHP code. If you are using the actual string 4288f0b8060ca1b682bf795f2617cfdc as the key passed into mcrypt_encrypt and mcrypt_decrypt then you aren't using the same key as in the Java code. You will need to convert that hex string into bytes. You can do this in the following way:

$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, pack("H*", $key), base64_decode($decrypt), MCRYPT_MODE_ECB, $iv);

Notice the addition of pack("H*", $key) to convert the value. I found that here in the comments for the PHP bin2hex function. This will fix the current problem. You may run into padding troubles when working with data of different lengths since PHP doesn't do PKCS5 padding. See this comment about implementing that missing function. Also, I'd recommend looking into CBC instead of ECB due to ECB's unsuitability and weaknesses for data encryption.

You can validate the output from your Java method at the command line using openssl. Java will default your IV to 0 if unspecified.

The file "enc.txt" contains "6GuKXA6FFR+yMmO8ksAEOLL5e574a5tLob7tt5IG+jk=" [corrected]

Run

openssl aes-128-ecb -in enc.txt -a -K 4288f0b8060ca1b682bf795f2617cfdc -iv 0 -d

The result is:

{"action":"getQuestion"}

Try your mcrypt_decrypt with an $iv value of 0.

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