我正在构建一个NodeJS客户端,用于使用256位块Rijndael CBC和PKCS7填充来加密数据的服务。
我看过NodeJS中的几个Rijndael实现,但似乎没有提供我正在寻找的组合。
有关如何在NodeJS中实现这一目标的任何建议?
我在这里发布的解决方案是我能够找到的,以防将来有人遇到同样的问题。
通过组合两个模块rijndael-js
和pkcs7-padding
(可从NPM注册表中获得),使用Rijndael 256块大小和PKCS7填充实际上很容易加密/解密。
rijndael-js
模块允许您使用各种块大小进行加密/解密:128,256和192块大小 - 但是,它仅支持零填充。未提供PKCS7填充支持。因此,您需要依赖另一个模块进行PKCS7填充,或者自己动手(也不是那么困难)。
如果长度不是块大小的倍数,rijndael-js
将只填充明文(要加密的数据)。为了防止它对数据进行零填充,必须先填写明文,然后再对其进行加密。在下面的例子中,我使用npm的pkcs7-padding
模块。
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);
这是如何解密数据
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