将AES Java解密代码移植到Node.js

时间:2014-02-09 04:26:59

标签: java javascript node.js encryption cryptography

我有以下Java代码,我想将其移植到Node.js:

// Java

byte[] rawKey = "deadbeefdeadbeef".getBytes("us-ascii");
SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES");
Cipher cip = Cipher.getInstance("AES/ECB/NoPadding");
cip.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] plaintext = cip.doFinal(ciphertext, 0, ciphertext.length);

这是我使用流

尝试使用Node.js
// JS, using the crypto streams API

var decipher = crypto.createDecipher('aes-128-ecb', 'deadbeefdeadbeef');
decipher.setAutoPadding(false);
decipher.pipe(concat(function(plaintext) { console.log(plaintext); });
decipher.end(ciphertext);

此外,Node.js还尝试使用较旧的.update().final() API:

// JS, using the `.update()` and `.final()` API

var decipher = crypto.createDecipher('aes-128-ecb', 'deadbeefdeadbeef');
decipher.setAutoPadding(false);
var pieces = [];
pieces.push(new Buffer(decipher.update(ciphertext)));
pieces.push(new Buffer(decipher.final()));
var plaintext = Buffer.concat(pieces);

这两个版本都生成相同长度的正确输出(与输入长度相同),但此输出与在相同输入缓冲区上运行的解码的Java版本生成的明文不同。如何设置Node.js解码,就像上面配置的Java解码一样?

谢谢。

1 个答案:

答案 0 :(得分:4)

createDecipher实际上并没有像在Java中那样使用密钥。它使用密码,该密码被输入基于密码的密钥派生函数(PBKDF)以派生密钥。因此,使用不同的密钥并且没有检查密钥正确性的方法,您将获得随机的纯文本。

Node.js API的命名不是很好,函数createDeciphercreateDecipheriv表明后者与前者相同,增加了IV。相反,createDecipher将整个密钥派生函数添加到混合中。