我正在为一项服务构建 NodeJS 客户端,该客户端使用带有 PKCS7 填充的 256 位块 Rijndael CBC 加密数据。
我在 NodeJS 中查看了几个 Rijndael 实现,但似乎没有一个提供我正在寻找的组合。
如何使用 Rijndael 算法实现加密?
关于如何在 NodeJS 中实现这一点的任何建议?
我在这里发布了我能够找到的解决方案,以防将来有人遇到同样的问题。
通过结合两个模块rijndael-js和pkcs7-paddingNPM 注册表中提供的模块,使用 Rijndael 256 块大小和 PKCS7 填充实际上非常容易加密/解密。
rijndael-js模块允许您使用各种块大小进行加密/解密:128、256 和 192 块大小 - 但是,它仅支持零填充。不提供 PKCS7 填充支持。因此,您要么需要依赖另一个模块进行 PKCS7 填充,要么自己完成(这也不是那么困难)。
rijndael-js如果其长度不是块大小的倍数,则只会对明文(要加密的数据)进行零填充。为了防止它填充零,您的数据必须在加密之前先填充明文。在下面的示例中,我pkcs7-padding为此使用了npm 中的模块。
nmp install rijndael-js pkcs7-padding --save
这就是你加密数据的方式
const Rijndael = require('rijndael');
const padder = require('pkcs7-padding');
const crypto = require('crypto');
const plainText = Buffer.from('Here is my plain text', 'utf8');
//Pad plaintext before encryption
const padded = padder.pad(plainText, 32); //Use 32 = 256 bits block sizes
const key = crypto.randomBytes(32); //32 bytes key length
const iv = crypto.randomBytes(32); //32 bytes IV
const cipher = new Rijndael(key, 'cbc'); //CBC mode
const encrypted = cipher.encrypt(padded, 256, iv);
Run Code Online (Sandbox Code Playgroud)
这是解密数据的方法
const encrypted = ... //holds our encrypted data
const key = ... // holds our 32 bytes key
const iv = ... //holds our 32 bytes iv
const decipher = new Rijndael(key, 'cbc');
const decryptedPadded = decipher.decrypt(encrypted, 256, iv);
//Remember to un-pad result
const decrypted = padder.unpad(decryptedPadded, 32);
const clearText = decrypted.toString('utf8');
console.log(clearText); //-> Here is my plain text
Run Code Online (Sandbox Code Playgroud)