首页 文章

Node.js加密输入/输出类型

提问于
浏览
4

我试图弄清楚Node.js加密库以及如何正确使用它来解决我的问题 .

我的目标是:

十六进制字符串中的键3132333435363738313233343536373831323334353637383132333435363738

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

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

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

这就是我所要做的,它没有像我期望的那样工作 . 我最好的猜测是输入和输出类型对于密码函数是不正确的 . 唯一有效的是utf8如果我使用hex它失败并出现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')

在这个例子中加密的输出是8cfdcda0a4ea07795945541e4d8c7e35,这不是我所期望的 .

1 回答

  • 1

    当您从中导出测试向量的网站使用 ecb 模式时,您的代码正在使用 aes-256-cbc . 此外,您正在调用 createCipher ,但使用ECB时,您应使用 createCipheriv 而不使用IV(请参阅nodeJS: can't get crypto module to give me the right AES cipher outcome),

    以下是一些演示此内容的代码:

    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
    

相关问题