3

在尝试理解Node.js Crypto API 时,我一直在尝试将代码与通过管道传输以进行十六进制显示的等效OpenSSL enc命令行(插入换行符以提高可读性)相匹配。xxd

$ echo -n "The quick brown fox jumps over the lazy dog" | openssl enc -aes256 -e
  -K "a891f95cc50bd872e8fcd96cf5030535e273c5210570b3dcfa7946873d167c57"
  -iv "3bbdce68b2736ed96972d56865ad82a2"  | xxd -p -c 64
582178570b7b74b000fd66316379835809874f985e0facadabb5b9c6b00593171165ae21c091f5237cea1a6fd939fd14

但是,当我运行时node test-aes.js,我得到以下输出:

b8f995c4eb9691ef726b81a03681c48e

这与我的预期输出不匹配(它甚至是长度的三分之一)。这是我的test-aes.js文件:

var crypto = require("crypto");

var testVector = { plaintext : "The quick brown fox jumps over the lazy dog",
    iv : "3bbdce68b2736ed96972d56865ad82a2",
    key : "a891f95cc50bd872e8fcd96cf5030535e273c5210570b3dcfa7946873d167c57",
    ciphertext : "582178570b7b74b000fd66316379835809874f985e0facadabb5b9c6b00593171165ae21c091f5237cea1a6fd939fd14"};

var key = new Buffer(testVector.key, "hex");
var iv = new Buffer(testVector.iv, "hex");
var cipher = crypto.createCipher("aes256", key, iv);
cipher.update(testVector.plaintext, "utf8");
var crypted = cipher.final("hex");
console.log(crypted);

问题:在将 OpenSSL 参数映射到 Node.js Crypto API 时我哪里出错了?

4

1 回答 1

3

给你:

var cipher = crypto.createCipheriv("aes256", key, iv);
var crypted = cipher.update(testVector.plaintext, "utf8", "hex");
crypted += cipher.final("hex");
console.log(crypted);

您的原始代码有两个问题

  1. createCipher是错误的功能,你应该使用createCipheriv.
  2. update有返回值,你需要跟踪它。
于 2013-03-04T03:14:07.130 回答