将OpenSSL命令行AES加密映射到NodeJS Crypto API等效项

时间:2013-03-04 02:59:36

标签: javascript node.js cryptography openssl aes

在尝试理解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加密API时出错了吗?

1 个答案:

答案 0 :(得分: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有一个返回值,您需要跟踪它。