John Davidson

javascript - cryptojs aes encryption does not match with php

0 comments
Message:


I want to encrypt and decrypt data between client and server so using cryptojs. but cryptojs does work properly



  1. it returns different values every time it runs when using AES but somehow decrypt properly.

  2. encrypted value does not match with php value.


php


$simple_string = "this is my test";
$ciphering = "AES-256-CBC";
$options = 0;
$encryption_iv = '0123456789012345';
$encryption_key = "password";
$encryption = openssl_encrypt($simple_string, $ciphering, $encryption_key, $options, $encryption_iv);

echo "Encrypted String: " . $encryption . " <br>"; // XkuEMQ6oPwCf4JFb7TlPgw==

$decryption=openssl_decrypt ($encryption, $ciphering, $encryption_key, $options, $encryption_iv);
echo "Decrypted String: " . $decryption; // this is my test

js


    function encrypt(msg, pass, iv) {
var encrypted = CryptoJS.AES.encrypt(msg, pass, { iv: iv, keySize: 256, mode: CryptoJS.mode.CBC, });
var decrypted = CryptoJS.AES.decrypt(encrypted, pass, { iv: iv, keySize: 256, mode: CryptoJS.mode.CBC, });

console.log(encrypted.toString()); // U2FsdGVkX19vi6PRshrz1aB0FSy0q4FNWvl3kkphsHs=
console.log(decrypted.toString(CryptoJS.enc.Utf8)); // this is my test
}
console.log(encrypt("this is my test", "password", "0123456789012345"));

i want javascript function(encrypt and decrypt) for sending and receiving server data using cryptojs.



My Answer:
The issue here is that the way you are using CryptoJS in your JavaScript code is not correct. The `CryptoJS.AES.encrypt` function returns an object, not a string. You need to convert this object to a string using `toString()` method with the desired encoding.

Here is the corrected JavaScript code:

javascript
function encrypt(msg, pass, iv) {
var encrypted = CryptoJS.AES.encrypt(msg, pass, { iv: iv, mode: CryptoJS.mode.CBC });
var decrypted = CryptoJS.AES.decrypt(encrypted, pass, { iv: iv, mode: CryptoJS.mode.CBC });

console.log(encrypted.toString()); // This will give you the encrypted string
console.log(decrypted.toString(CryptoJS.enc.Utf8)); // This will give you the decrypted string
}

encrypt("this is my test", "password", CryptoJS.enc.Utf8.parse("0123456789012345"));


Make sure to parse the IV string to the correct format using `CryptoJS.enc.Utf8.parse` before passing it to the `encrypt` function.

With these changes, the encrypted value generated by CryptoJS should match the one generated by PHP.

Rate this post

4 of 5 based on 9820 votes

Comments




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