4

我正在尝试找出 Node.js Crypto 库以及如何根据我的情况正确使用它。

我的目标是:

键入十六进制字符串 3132333435363738313233343536373831323334353637383132333435363738

十六进制字符串中的文本 46303030303030303030303030303030

十六进制字符串中的密文 70ab7387a6a94098510bf0a6d972aabe

我正在通过 AES 256 的 ac 实现和通过http://www.hanewin.net/encrypt/aes/aes-test.htm的网站对此进行测试

这是我必须要做的,它没有按照我期望的方式工作。我最好的猜测是密码函数的输入和输出类型不正确。唯一有效的是utf8,如果我使用十六进制它会失败并出现v8错误。关于我应该转换或更改以使其正常工作的任何想法。

var keytext = "3132333435363738313233343536373831323334353637383132333435363738";
var key = new Buffer(keytext, 'hex');
var crypto = require("crypto")
var cipher = crypto.createCipher('aes-256-cbc',key,'hex');
var decipher = crypto.createDecipher('aes-256-cbc',key,'hex');

var text = "46303030303030303030303030303030";
var buff = new Buffer(text, 'hex');
console.log(buff)
var crypted = cipher.update(buff,'hex','hex')

在这个例子中,crypted 的输出是 8cfdcda0a4ea07795945541e4d8c7e35,这不是我所期望的。

4

1 回答 1

1

aes-256-cbc当您从中派生测试向量的网站正在使用模式时,您的代码正在使用ecb。另外,您正在调用createCipher,但是对于 ECB,您应该不使用createCipherivIV(请参阅nodeJS: can't get crypto module to give me the right AES cipher results),

下面是一些演示这一点的代码:

var crypto = require("crypto");

var testVector = { plaintext : "46303030303030303030303030303030",
    iv : "",
    key : "3132333435363738313233343536373831323334353637383132333435363738",
    ciphertext : "70ab7387a6a94098510bf0a6d972aabe"};

var key = new Buffer(testVector.key, "hex");
var text = new Buffer(testVector.plaintext, "hex");
var cipher = crypto.createCipheriv("aes-256-ecb", key, testVector.iv);
var crypted = cipher.update(text,'hex','hex');
crypted += cipher.final("hex");
console.log("> " + crypted);
console.log("? " + testVector.ciphertext);

运行该代码的输出并不完全符合我的预期,但加密输出的第一个块符合您的预期。可能是另一个需要调整的参数。:

$ node test-aes-ecb.js 
> 70ab7387a6a94098510bf0a6d972aabeeebbdaed7324ec4bc70d1c0343337233
? 70ab7387a6a94098510bf0a6d972aabe
于 2015-01-12T15:48:54.637 回答