我有以下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解码一样?
谢谢。
答案 0 :(得分:4)
createDecipher
实际上并没有像在Java中那样使用密钥。它使用密码,该密码被输入基于密码的密钥派生函数(PBKDF)以派生密钥。因此,使用不同的密钥并且没有检查密钥正确性的方法,您将获得随机的纯文本。
Node.js API的命名不是很好,函数createDecipher
和createDecipheriv
表明后者与前者相同,增加了IV。相反,createDecipher
将整个密钥派生函数添加到混合中。