AES - Crypto JS & PHP

I've problem with decryption data encrypted in cryptojs. Sometimes it works sometimes not, if works it returns "Message", but if dosent it returns garbage.

    var salt = CryptoJS.lib.WordArray.random(128/8); 
    var key256Bits500Iterations = CryptoJS.PBKDF2("password", salt, { keySize: 256/32, iterations: 5 });
    var iv  = CryptoJS.enc.Hex.parse('1011121c1d1e1f');
    var encrypted = CryptoJS.AES.encrypt("Message", key256Bits500Iterations, { iv: iv });  
    var data_base64 = encrypted.ciphertext.toString(CryptoJS.enc.Base64); 
    var iv_base64   = encrypted.iv.toString(CryptoJS.enc.Base64);       
    var key_base64  = encrypted.key.toString(CryptoJS.enc.Base64);


 $encrypted = base64_decode($_POST['data']); /
    $iv        = base64_decode($_POST['iv']);
    $key       = base64_decode($_POST['key']); 
    $plaintext = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, rtrim($key, "\t\0\r\n "), rtrim($encrypted, "\t\0\r\n "), MCRYPT_MODE_CBC, $iv ), "\t\0\r\n ");

I would like to stay on cryptoJS.



Finally i've ended with:

but it still needed some tweaking so:

$crypted = rtrim($_POST['msg'],'\t\0\r\n ');
$crypted = str_replace(" ","+",$crypted);
$password = 'itsmysecret';
$blocksize = 256; 
$decrypted =  AES::decrypt($crypted, $password, $blocksize);

Now it works.


You shouldn't rtrim the key. The key may contain any byte value, including the ones you just trimmed away. Older versions happily fill the key up with 0 valued bytes, so that means that the key may differ from the one used in the CryptoJS source.

Sending the key with the ciphertext doesn't make sense. Instead it is best to use PBKDF2 in PHP as well and calculate the key from a password.

Finally, note that PHP mcrypt defaults to zero padding, unpad using PKCS#7 instead. The comments for mcrypt on the help pages contain a good PKCS#7 implementation to perform the unpadding.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.