I'm trying to encrypt the json data in PHP and JAVA. But unable to match the response of both.
Can we generate IV(Initialization Vector) value based on specific parameter?
In PHP, we have functions to do. I'm trying to encrypt the data using below function and passing $iv as one of the parameter.
$secretKey= 'BDGAJDL7AGSNPBST';
PHP:
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
(or)
$iv = bin2hex(openssl_random_pseudo_bytes(static::INIT_VECTOR_LENGTH / 2));
// Encrypt input text
$encryptedPayload = openssl_encrypt($plainText,static::CIPHER,$secretKey,OPENSSL_RAW_DATA,$iv);
(or)
$encryptedPayload = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $secretKey, $plainText, MCRYPT_MODE_CBC, $iv);
The above PHP function is always returns different value. IV is meant to provide unique values every time.
I'm trying to match the return value of below JAVA code. Which is always returning same encrypted string.
JAVA
try{
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes(UTF_8), "AES");
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(encryptionKey.getBytes(UTF_8)));
response = cipher.doFinal(convertPOJOtoJSON(user).getBytes(UTF_8));
}catch (Exception e) {
//
}
return response;
You really should not have to "match" an IV. The IV along with an HMAC should be appended to the cipher text. Just as long as the PHP and the JS parse the IV and HMAC from cipher text string the same way you will be just fine.
An IV is really just a random string of a certain length that is used to seed/salt your encryption and is not dependent on a key.
A HMAC is a hash of the cipher text(that is dependent on the key) that is used to authenticate the cipher text before decrypting. This HMAC is appended to the cipher text along with the IV. Before decrypting you will hash the cipher text and compare it with the hash appended to the cipher text. If they match then nothing has been tampered with. If they don't match you should consider the data to be compromised.
I would recommend using the Libsodium library for your encryption needs. It is now native for the latest version of PHP and you can also find it for JS.
Libsodium - PHP
Libsodium - JS
Here is a good doc to get you started.
A good encryption/authentication read