In PHP, I am unable to decrypt a string encrypted in java using AES CBC 128 bit. I have tried bott phpseclib and openssl on the PHP side. Though my preference is for phpseclib.
Java Side
-
I generated an AES 128 bit key using:
keyGen = KeyGenerator.getInstance("AES"); keyGen.init(128); secretKey = keyGen.generateKey();
-
Generated an initialization vector by getting bytes from a string:
byte[] iv = "myuniqueivparam".getBytes("UTF-8");
-
Encrypted a string as follows:
Cipher enCipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
// the key and iv are passed on to php as strings
PHP side
-
Set the algorithm:
$aes = new Crypt_AES(CRYPT_AES_MODE_CBC);
-
The key and iv I got from java are passed as strings:
$aes->setKey($userKey); $aes->setKeyLength(128); // when I echo this I get myuniqueivparam $ivdecode=base64_decode($iv); $aes->setIV($ivdecode);
-
Set the same input and add padding
$input="winning"; $blocksize = 16; $pad1=$blocksize -(strlen($input) %$blocksize); $input1=$input . str_repeat(chr($pad1), $pad1);
-
Encrypted the string using phpseclib:
$aes = new Crypt_AES(CRYPT_AES_MODE_CBC); $dummy = base64_encode($aes->encrypt($input1)); echo $dummy;
$decryptedstring=$aes->decrypt($encryptedStringInJava);
Issues
When I print
$dummy
, in step 4, the encrypted string that I get does not match the encrypted string from java.Decrypting
$encryptedStringInJava
is not working in PHP (step 5)
I have tried encryption/decryption in java using both phpseclib and openssl.