javascriptphpencryptioncryptojscryptdecrypt

Encrypt string with CryptoJS in Javascript and decrypt in PHP with openssl_decrypt - Not working


In my Angular application I need to encrypt a string and send it to a remote server where PHP should decrypt it. I'm using the javascript library CryptoJS. PHP version is 7.4. All combinations I tried failed.

I read similar questions here and tried to implement their code in my application, but I couldn't find a way to get it done.

I always end up in PHP with the openssl error:

error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt.

Here is my last code:

const q = 'hello world';
const cryptKey = 'a';
const secretKey = CryptoJS.MD5(cryptKey).toString();
const iv = CryptoJS.enc.Hex.parse(CryptoJS.MD5(CryptoJS.MD5(cryptKey).toString()).toString());
let encrypted = CryptoJS.AES.encrypt(q, secretKey, {
  iv: iv
});
let encoded = CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
$cryptKey = 'a'; 
$encoded = "r+crKP3pmlRoAovRPCK2dQ=="; //= encoded in javascript

$decrypted = openssl_decrypt(base64_decode($encoded), "aes-256-cbc", md5($cryptKey), 0, md5(md5($cryptKey)));

Solution

  • I found this question with an answer that helped me solve my problem. Thanks @Topaco