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

时间:2014-08-02 20:52:24

标签: javascript php node.js encryption

我正在尝试将这个工作的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);

3 个答案:

答案 0 :(得分:3)

MCRYPT_RIJNDAEL_256是指具有256位的非标准块大小的rijndael加密算法,而不是{em>密钥大小 { {1}}位。 PHP使用256进行加密,而Node.js使用libmcrypt,而libmcrypt实现AES(块大小为128位),它还实现了具有可配置块大小的rijndael。

AES具体定义为128位的块大小,这是rijndael openssl支持的唯一版本。因此,我为名为node-rijndael的节点编写了一个最小的libmcrypt绑定,它应该用于您的目的。另请参阅我对类似问题的回答here

openssl

答案 1 :(得分:0)

尝试使用node.js:

这样的内容
var aes_iv_b = new Buffer(aes_iv, 'base64'),
    shared_key_b = new Buffer(shared_key, 'hex'),
    decipher = crypto.createDecipheriv('aes-256-cbc', shared_key_b, aes_iv_b),
    decoded = Buffer.concat([
      decipher.update(payload, 'base64'),
      decipher.final()
    ]);
// if the output is utf8/ascii you might be able to improve performance by using
// something like this instead:
//  decoded = decipher.update(payload, 'base64', 'utf8') // or 'ascii'
//            + decipher.final('utf8'); // or 'ascii'

console.log(decoded);

答案 2 :(得分:0)

如果您能够将openssl改为使用aes-256-cbc而不是libmcrypt更改PHP代码,那么您可以使用我使用过的标准crypto库在另一个answer

希望它有所帮助。 问候, 伊格纳西奥