Skip to content Skip to sidebar Skip to footer

Implement Php Open_ssl_decrypt Aes 256 Cbc As Cryptojs

I try to make the following code in ReactJs (not NodeJs) but this doesn't work in JS. The original code in PHP works fine: function decryptOpensslDigestSHA256Sum($data) {

Solution 1:

The PHP implementation uses EVP_BytesToKey() as key derivation function and is thus compatible with the CryptoJS key derivation.

However, CryptoJS applies MD5 as digest by default, while the PHP code uses SHA256 (note that OpenSSL has changed the default digest from MD5 to SHA256 as of version v1.1.0). Moreover, the password applied for the key derivation function is not the password itself (i.e. Nootric2703202) but the hex encoded SHA256 hash of the password.

If this is taken into account, decryption with CryptoJS is:

var password = 'Nootric2703202';
var passwordHashWA = CryptoJS.SHA256(password);
var passwordHashHex = passwordHashWA.toString(CryptoJS.enc.Hex); 

var ciphertext = 'U2FsdGVkX1++7PN6CsF5Bi38t0N3EjXpH5oGpaIZXUwk4T8QCwcATjvA4b/8VaxD8nf/MZhKPnWb1L8raLR4lw==';

CryptoJS.algo.EvpKDF.cfg.hasher = CryptoJS.algo.SHA256.create();           
var data = CryptoJS.AES.decrypt(ciphertext, passwordHashHex);
console.log(data.toString(CryptoJS.enc.Utf8));
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>

which produces the expected plaintext:

email=abc@xyz.abc&name=&gpw_id=gpwID

Due to OpenSSL compatibility, the ciphertext can also be decrypted with the following OpenSSL expression:

openssl enc -aes-256-cbc -d -md sha256 -in <ciphertextFile> -k d0f95d5e54a7aa25934a5d4915c9e2a06dadac20d16551693be1d21d4d8e8798 -A -a -p

where <ciphertextFile> is the path to a file containing the Base64 encoded ciphertext (without linebreaks): U2FsdGVkX1..., and the password d0f95d... is the hex encoded SHA256 hash of the password Nootric2703202.

Please keep in mind that EVP_BytesToKey() is considered insecure, s. e.g. here. Instead, a reliable key derivation function like PBKDF2 should be used.

Post a Comment for "Implement Php Open_ssl_decrypt Aes 256 Cbc As Cryptojs"