Mapping OpenSSL command line AES encryption to NodeJS Crypto API equivalent

筅森魡賤 提交于 2019-12-10 10:19:00

问题


In trying to understand the Node.js Crypto API, I have been trying to match code to the equivalent OpenSSL enc command line (line breaks inserted for readability) which is piped through xxd for hex display.

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

However, when I run node test-aes.js, I get the following output:

b8f995c4eb9691ef726b81a03681c48e

Which does not match my expected output (it is even one third the length). Here is my test-aes.js file:

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

Question: Where am I going wrong in mapping the OpenSSL parameters to the Node.js Crypto API?


回答1:


Here ya go:

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

You have two issues with your original code

  1. createCipher is the wrong function, you should be using createCipheriv.
  2. update has a return value, you need to keep track of it.


来源:https://stackoverflow.com/questions/15193913/mapping-openssl-command-line-aes-encryption-to-nodejs-crypto-api-equivalent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!