AES - Crypto JS & PHP

坚强是说给别人听的谎言 提交于 2020-01-25 15:32:32

问题


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);

PHP

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


回答1:


Finally i've ended with: http://wiki.birth-online.de/snippets/php/aes-rijndael http://wiki.birth-online.de/snippets/javascript/aes-rijndael

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.




回答2:


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.



来源:https://stackoverflow.com/questions/27452342/aes-crypto-js-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!