PHP中使用OpenSSL进行AESencryption/在Node.js中解密

我正在使用PHP和Nodejs与OpenSSL进行对称encryption。 PHP使用OpenSSL库,Node.js解密基于实现的encryption。 问题是Node.js中的解密文本只是部分正确的

PHP函数进行encryption

function encrypt($text, $pw, $base64 = true) { $method = 'aes-256-cbc'; $iv_len = openssl_cipher_iv_length($method); $iv = openssl_random_pseudo_bytes($iv_len); $pw = substr(md5($pw),0,32); $cipher = openssl_encrypt ($text ,$method ,$pw ,!$base64 ,$iv ); if($base64) { $pw = base64_encode($pw); $iv = base64_encode($iv); } return array( 'iv' => $iv, 'pw' => $pw, 'text' => $text, 'cipher' => $cipher ); } 

在nodejs解密

 var cipher = new Buffer(data.cipher, 'base64'); var iv = new Buffer(data.iv, 'base64'); // the password is the same returned by the php function, so 100% correct var key = new Buffer(data.pw, 'base64'); var dec = crypto.createDecipheriv('aes-256-cbc',key,iv); var dec_data = dec.update(cipher,'binary','utf8'); // the script is based on socket.io socket.emit('debug',{decrypted : dec_data}); 

结果

 # Encrypting in php... >> encrypt('1. Lorem ipsum dolor sit amet! 2. Lorem ipsum dolor sit amet!', 'password'); # ...makes nodejs giving me something like >> 1, 6+r@o ipsum /olor sit amet! 2. Lorem ipsum do 

我猜这个问题可能与填充有关 – 但说实话:我不知道。

感谢您阅读帮助!

在你的节点代码中,你错过了消息的最后部分:

 var dec = crypto.createDecipheriv('aes-256-cbc',key,iv); var dec_data = dec.update(cipher,'base64','utf8') + dec.final('utf8'); 

另外,使用base64解码,而不是二进制(因为它可能会落在这里提到的情况下https://stackoverflow.com/a/8770975/3739618

我有这个示例代码工作在这个其他职位,请检查出来: https : //stackoverflow.com/a/28181444/3739618

问候,伊格纳西奥