我在这里发布了我能够找到的解决方案,以防将来有人遇到同样的问题。
实际上,通过组合两个模块,使用 Rijndael 256 块大小和 PKCS7 填充来加密/解密非常容易rijndael-js
and pkcs7-padding
可从 NPM 注册表获取。
rijndael-js
模块允许您使用各种块大小进行加密/解密:128、256 和 192 块大小 - 但是,它仅支持零填充。不提供 PKCS7 填充支持。因此,您要么需要依赖另一个模块来进行 PKCS7 填充,要么自己完成(这也不是那么困难)。
rijndael-js
如果明文(要加密的数据)的长度不是块大小的倍数,则只会对明文(要加密的数据)进行零填充。为了防止它进行零填充,您的数据必须在加密之前首先填充明文。在下面的示例中,我使用pkcs7-padding
npm 的模块。
npm install rijndael-js pkcs7-padding --save
这就是加密数据的方式
const Rijndael = require('rijndael-js');
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);
这是解密数据的方法
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