【问题标题】:Node.js Crypto input/output typesNode.js 加密输入/输出类型
【发布时间】:2012-08-19 14:58:29
【问题描述】:

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

我的目标是:

键入十六进制字符串 3132333435363738313233343536373831323334353637383132333435363738

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

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

我正在通过 AES 256 的 c 实现以及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,这不是我所期望的。

【问题讨论】:

  • 您的目标意味着没有静脉注射。你真的想要那个吗?我还强烈建议添加 MAC。
  • 我怀疑加密库会自动添加随机 IV 和填充,从而产生 3 块(48 字节)的输出。在大多数情况下,这比无填充 ECB 更合适。
  • 我打算使用静脉注射,为了简化问题,我省略了它。我不确定你所说的 MAC 是什么意思?
  • 完整性检查,确保没有人篡改您的密文。没有它,您将面临许多攻击,例如填充预言。
  • 查看 NodeJS 文档,我只看到一个有两个参数的 createCipher 工厂方法。你用的是什么版本&上面的代码有没有测试过?

标签: javascript node.js encryption aes node-crypto


【解决方案1】:

当您从中派生测试向量的网站使用ecb 模式时,您的代码使用aes-256-cbc。此外,您正在调用 createCipher,但对于 ECB,您应该使用不带 IV 的 createCipheriv(参见 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 2014-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多