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

我有我想要移植到Node.js的以下Java代码:

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

这是我使用stream的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); 

这两个版本都会产生正确长度的输出(与input长度相同),但是这个输出与在相同input缓冲区上运行的解密Java版本产生的明文不同。 如何设置像上面configuration的Java解码器一样的Node.js解码?

谢谢。

实际上, createDecipher不像在Java中那样使用密钥。 它使用一个密码,input一个基于密码的密钥派生函数(PBKDF)来派生密钥。 因此,用一个不同的密钥,没有检查密钥的正确性的方法,你会得到随机的纯文本。

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