2

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
  • Stick to openssl_encrypt(). Best method is AES-256-CTR and of course use IV with 16 chars. Commented Dec 30, 2017 at 9:22

1 Answer 1

1
  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.

Sign up to request clarification or add additional context in comments.

1 Comment

Good answer. To future readers, also note that as of PHP 7.1, AES in GCM mode is supported, which is likely a better fit for new work than CTR mode since it eliminates the need for an HMAC.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.