John Davidson

javascript - CryptoJS aes encrypt function PHP equivalent

0 comments
Message:


I am trying to create a PHP equivalent to this JS code with CryptoJS:


function aesEncrypt (data) {
const key = 'GSTEGSTEjdfheyhdHSHSHSHDHHDHmdjjdn12ndndn5r=';
const iv = '\0';

const cipher = CryptoJS.AES.encrypt(data, CryptoJS.enc.Base64.parse(key), {
iv: CryptoJS.enc.Utf8.parse(iv), // parse the IV
padding: CryptoJS.pad.Pkcs7,
mode: CryptoJS.mode.CBC
})

return cipher.toString()
}

result of the js code : pHjpwiyKq7Rf4dFcBMbm1w==


here is the PHP code I wrote by reading other stackoverflow questions. But it did not return the same result.


    $plaintext  = "plainText";
$method = 'aes-256-cbc';

$key = base64_encode("GSTEGSTEjdfheyhdHSHSHSHDHHDHmdjjdn12ndndn5r=");
$iv = hex2bin('00000000000000000000000000000000');

$ciphertext = openssl_encrypt(
$plaintext,
$method,
$key,
OPENSSL_RAW_DATA,
$iv
);

$ciphertext = base64_encode($ciphertext);

echo $ciphertext;

result of the PHP code : +YJOMi2vISmEXIjUZls3MA==



My Answer:
To make the PHP code equivalent to the JavaScript code using CryptoJS, you need to make sure that the key and IV are properly formatted and used in the encryption process. Here is the corrected PHP code:

php
function aesEncrypt($data) {
$key = base64_decode("GSTEGSTEjdfheyhdHSHSHSHDHHDHmdjjdn12ndndn5r=");
$iv = "\0";

$cipher = openssl_encrypt(
$data,
'aes-256-cbc',
$key,
OPENSSL_RAW_DATA,
$iv
);

return base64_encode($cipher);
}

$plaintext = "plainText";
$result = aesEncrypt($plaintext);
echo $result;


This PHP code should now produce the same result as the JavaScript code using CryptoJS.

Rate this post

3 of 5 based on 4636 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us