JavaScript-Node.js中的PHP aes-256-cbc mcrypt_decrypt()等效项

我正在尝试将此工作的PHP代码移植到Node.js,但出现错误:IV长度无效32

这是PHP代码:

//--- PHP example code (works): ---

$aes_iv = 'MjY2YjljMmM0MjVjNzVlMGMyZGI2NjAwN2U5ZGMzZDQ%3D';

$payload = base64_decode($payload);
$aes_iv = base64_decode($aes_iv);

// secret key. 64 character hex string:
$shared_key = '14370ced836 ...'; 
// convert from hex to binary string:
$shared_key = pack('H*', $shared_key); 

// AES decrypt payload
$payload = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $shared_key, $payload, MCRYPT_MODE_CBC, $aes_iv);


// AES adds null characters to the end of short strings, 
// so we should strip them out
$payload = rtrim($tp_payload, "\0"); 

这是不起作用的Node.js代码.
请参阅“错误:无效的IV长度32”

//--- Node.js equivalent ??? ---

var aes_iv = 'MjY2YjljMmM0MjVjNzVlMGMyZGI2NjAwN2U5ZGMzZDQ%3D';

var payload_s = new Buffer(payload, 'base64').toString();
var aes_iv_s = new Buffer(aes_iv, 'base64').toString();

// secret key. 64 character hex string:
var shared_key = '14370ced836 ...'; 
// convert from hex to binary string:
var shared_key_b = new Buffer(shared_key, 'hex').toString('binary');

// Error: Invalid IV length 32
var decipher = crypto.createDecipheriv('aes-256-cbc', shared_key_b, aes_iv_s);
var decoded  = decipher.update(payload_s);

decoded += decipher.final();
console.log(decoded);

解决方法:

MCRYPT_RIJNDAEL_256是指rijndael加密算法,其非标准块大小为256位,而不是密钥大小为256位. PHP使用libmcrypt进行加密,而Node.js使用openssl,而libmcrypt实现AES(块大小为128位),它也实现具有可配置块大小的rijndael.

AES是用128位的块大小专门定义的,这是rijndael openssl支持的唯一版本.这样,我为名为node-rijndael的节点编写了一个最小的libmcrypt绑定,该绑定应该可以满足您的目的.另请参阅我对类似问题here的回答.

var Rijndael = require('node-rijndael');

// shared_key
var key = '14370ced836...';

// aes_iv
var iv = new Buffer('MjY2YjljMmM0MjVjNzVlMGMyZGI2NjAwN2U5ZGMzZDQ=', 'base64');

var payload = new Buffer(/*payload*/);

var rijndael = new Rijndael(key, {
  mode: Rijndael.MCRYPT_MODE_CBC,
  encoding: 'hex', // shared_key encoding
  iv: iv
});

// defaults to utf-8 output encoding
payload = rijndael.decrypt(payload);
payload = payload.replace(/\0+$/, '');
上一篇:PHP-openssl_encrypt,openssl_decrypt密钥,iv


下一篇:C#中应用程序配置文件的“静态”加密