U
U
Username2021-02-19 11:33:19
PHP
Username, 2021-02-19 11:33:19

How to decrypt with AES 128-CBC on Crypto-JS?

Good afternoon!
There is a PHP code that decrypts the payload with a secret key, I try to write exactly the same JavaScript code using the crypto-js library , but I get the wrong result.

The first 16 bytes in payload is a vector, the rest is useful information.

  1. Working code in PHP - https://ideone.com/NJXkRK
  2. Non-working JS code - https://codepen.io/perec200/pen/ExNXMpO

Please help me improve my JS code

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
galaxy, 2021-02-19
@galaxy

...
  const data = aes_128_decrypt(encryption_key, base64_original);

  console.log(data);
}

function aes_128_decrypt(password, data) {
  let iv = data.substr(0, 16);
  let payload = data.substr(16);

  iv = CryptoJS.enc.Hex.parse(iv);
...

And where did you actually do the decoding from base64?
You don't need to parse hex either.

P
profesor08, 2021-02-19
@profesor08

1. decrypted.toString(CryptoJS.enc.Utf8)
2. You are corrupting the data, or converting it in the wrong order.
3. Different algorithms, you need to specify which one is encrypted in js and in php
Because encryption and decryption works like this:

let message = `{"store_id":20553036,"access_token":"secret_a9TmTJfRt3gyvxjJ9UwYjs9VQip3F7rp","public_token":"public_QQ99gUwVGdvKuZbLLyNZzDsvXF5iF3gh","view_mode":"PAGE","lang":"ru"}`;

let secret = `zcKf1Zt0UsO43S46Un3pxIgs91R1xMGs`;

const ciphertext = CryptoJS.AES.encrypt(message , secret).toString();
const bytes  = CryptoJS.AES.decrypt(ciphertext, secret);
const originalText = bytes.toString(CryptoJS.enc.Utf8);

console.log(ciphertext); 
console.log(originalText);

$message = '{"store_id":20553036,"access_token":"secret_a9TmTJfRt3gyvxjJ9UwYjs9VQip3F7rp","public_token":"public_QQ99gUwVGdvKuZbLLyNZzDsvXF5iF3gh","view_mode":"PAGE","lang":"ru"}';

$secret = "zcKf1Zt0UsO43S46Un3pxIgs91R1xMGs";

$ciphertext = openssl_encrypt($message, "aes-128-cbc", $secret);
$originalText = openssl_decrypt($ciphertext, "aes-128-cbc", $secret);

echo $ciphertext . PHP_EOL;
echo $originalText;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question