简体   繁体   中英

AES encryption using Php , javascript and vise versa

I am doing client side encryption using javascript and server side using PHP. Both side we are using same key and IV.

Php Encryption :

$string='test data';

$output = '';
    $encrypt_method = 'AES-256-CBC';
    $secret_key     = 'secret key in hex';
    $secret_iv      = 'iv in hex';
    $key            = hash('sha256',$secret_key);

$output   = openssl_encrypt($string,$encrypt_method,$key,0,$initialization_vector);

//Encrypted text in php
$output   = base64_encode($output);

Javascript Encryption Code:

var key = 'secret key in hex';
key = CryptoJS.SHA256(key);            
var ivHex = CryptoJS.enc.Hex.parse(' IV in hex ');            
var options = { mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7, iv:ivHex};
var obj='test data';
var encrypted = CryptoJS.AES.encrypt(obj,key ,options);
var encryptedBase64 = encrypted.toString();

//Encrypted text in javascript    
console.log(encryptedBase64);

Both are giving different output. Am I doing anything wrong?

  1. $secret_iv is defined, but an undefined $initialization_vector is used in openssl_encrypt() .
  2. For the fourth argument, you don't want to pass 0 , you want to pass OPENSSL_RAW_DATA (a constant).
  3. You're passing hash('sha256', $secret_key) in PHP but using secret_key directly in Javascript.
    • Note: Your key derivation ( hash('sha256', $some_text_input) ) is very weak. Consider PBKDF2-SHA256 instead.

Important: AES-CBC without an HMAC is vulnerable to padding-oracle attacks . You should always use authenticated encryption .

An example of secure encryption looks like this . Decryption is a little more involved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM