node.js - 使用 Node.js 加密进行 PKCS5 填充

标签 node.js cryptography node-crypto

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

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 字节。我错过了什么?

最佳答案

首先,您通过忽略 aesCipher.update() 的返回值来丢弃加密内容的第一部分。另外,由于您的 update() 没有指定输出编码,因此它返回一个 Buffer,而您的 final() 返回一个“二进制”字符串。您可以尝试:

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

关于node.js - 使用 Node.js 加密进行 PKCS5 填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23915367/

相关文章:

node.js - NodeJS Expres + RedisStore ,请求 session 始终未定义

node.js - 使用 node-sqlite 将数据从一个数据库复制到另一个数据库 - 格式化 'insert' 语句

delphi - Delphi XE 中的 SHA1 哈希

c++ - 如何跨平台使用Poco C++库的FIPS模式?

javascript - Node.js v6.2.2 crypto.createCipheriv "Invalid key length"错误

node.js - 让 SASS 使用 NodeJS Express 和 node-sass 自动编译

node.js - 如何在 Nodejs Azure Cosmos 中覆盖文档

C++ Pseudo-RSA 快速求解大量的 d(解密 key )

node.js - 在 Node.js 中使用 Crypto 时的错误处理