使用node.js加密的PKCS5填充

时间:2014-05-28 15:07:22

标签: node.js cryptography node-crypto

node.js crypto的文档表明填充是自动插入到输入流中的。我有一个简单的测试程序,需要计算明文的SHA1哈希,然后加密该20字节哈希使用AES-256 / CBC和PKCS5填充。这是我的测试代码:

var fs = require('fs');
var crypto = require('crypto');

var key = [ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
            0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
            0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
            0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f ];

var iv = [ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
           0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f ];

var test_string = "This is the string I am signing";

// Create SHA1 hash of our string
var sha1Hash = crypto.createHash("sha1");
sha1Hash.update(test_string, "utf8");
var sha1 = sha1Hash.digest();

var aesCipher =
        crypto.createCipheriv("aes-256-cbc", (new Buffer(key)), (new Buffer(iv)));
aesCipher.update(sha1, "binary");
var encrypted = aesCipher.final("binary");

fs.writeFile('data/node_encrypted.bin', encrypted, function (error) {
    if (error)
        throw error;
    console.log("File saved!");
});

但是,这会生成一个长度仅为23个字节的文件。我期望通过适当的PKCS5填充,输出将是32字节。我错过了什么?

1 个答案:

答案 0 :(得分:3)

首先,您通过忽略aesCipher.update()的返回值来丢弃加密内容的第一部分。此外,由于您的update()未指定输出编码,因此它返回缓冲区,但您的final()正在返回“二进制”字符串。您可以尝试改为:

var encrypted = Buffer.concat([
  aesCipher.update(sha1, "binary"),
  aesCipher.final()
]);
相关问题