微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Node.js Crypto En- / Decrypting Buffer 以某种方式减小了大小

如何解决Node.js Crypto En- / Decrypting Buffer 以某种方式减小了大小

我正在尝试使用 AES-256-CBC 加密文本。为此,我使用 node.js 加密模块。 现在我在理解某些东西时遇到了困难。我将我的纯文本转换为缓冲区,并希望以这种方式将其传递给密码。纯文本的缓冲区大小是 53 个字节(这是正确的,因为它也是 53 个字符长)。但是在 cipher.update() 运行后,结果缓冲区只有 48 个字节。这怎么可能?

// Generate ivBytes depending on the (byte) size of the used algorithm
const ivBytes = itf.generaterandomBytes(options.ivByteSize);
// create the cipher with the used algorithm,key and the generated ivBytes
const cipher = itf.createCipherIV(options.algorithm,key,ivBytes);

let plainBytes = Buffer.from(plainText,"utf-8");

let cipherBytes = cipher.update(plainBytes);

cipherBytes = cipher.final();

//  combine ivBytes with cipherBytes
//   |----------- ivBytes -----------|----------- cipherBytes -------------|
//   \___________ 16  Byte _________/ \______________x Bytes_______________/
// |                                                                        |
//  \______________________________________________________________________/
//                                        V
//                              encode this combination

let ivAndCipherBytes = null;
// attach ivBytes to back or front of cipherBytes
if (options.ivAtBack) {
  ivAndCipherBytes = Buffer.concat([cipherBytes,ivBytes]);
} else {
  ivAndCipherBytes = Buffer.concat([ivBytes,cipherBytes]);
}

以下是查看调试器中缓冲区大小的屏幕截图:

screenshot to see the inline size of the buffers

我希望它是 64 字节长,因为:

  • AES 的块大小为 16 字节
  • 53 字节 / 16 字节 = 3,3 -> 16 字节 * 4 = 64 字节

计数器部分是一个 C# WPF 应用程序,它使用 System.Security.Cryptography 库,其行为与预期相同,并为上述示例返回 64 字节数组。

我真的不想像在 node.js 加密文档中那样使用 cipher.update() 函数,因为我想将 iv 作为缓冲区附加到加密缓冲区并在发送之前将其全部编码。>

有人能帮我解决这个问题或给我指明正确的方向吗? 提前致谢!

解决方法

@Ebbe M. Pedersen 和用户 9014097 已在评论中提及。我需要将更新函数的结果与最终函数的结果连接起来,如下所示:

// get the plainText Bytes
let plainBytes = Buffer.from(plainText,"utf-8");
// feed them to the cipher (which could be done multiple times
let cipherBytes = cipher.update(plainBytes);
// but at the end attach the result of the final block
cipherBytes = Buffer.concat([cipherBytes,cipher.final()]);

这将返回一个预期大小为 64 的字节数组。谢谢帮助!我只见树木不见森林!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。