在 NodeJS 中加密和解密数据
NodeJS提供了内置的加密库来加密和解密NodeJS中的数据。我们可以使用这个库来加密任何类型的数据。您可以对字符串、缓冲区甚至数据流进行加密操作。加密还包含用于加密的多种加密算法。请查看官方资源以获取相同信息。在本文中,我们将使用最流行的AES(高级加密标准)进行加密。
配置“加密”依赖
在您的项目中,检查NodeJS是否已初始化。如果没有,请使用以下命令初始化NodeJS。
>> npm init -y
手动安装节点时会自动添加“crypto”库。如果没有,您可以使用以下命令安装加密。
>> npm install crypto –save
示例
加密和解密数据
//检查加密模块
const crypto = require('crypto');
const algorithm = 'aes-256-cbc'; //使用AES加密
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
//加密文本
function encrypt(text) {
let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv);
let encrypted = cipher.update(text);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return { iv: iv.toString('hex'), encryptedData: encrypted.toString('hex') };
}
//解密文本
function decrypt(text) {
let iv = Buffer.from(text.iv, 'hex');
let encryptedText = Buffer.from(text.encryptedData, 'hex');
let decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(key), iv);
let decrypted = decipher.update(encryptedText);
decrypted = Buffer.concat([decrypted, decipher.final()]);
return decrypted.toString();
}
//文本发送加密功能
var hw = encrypt("Welcome to nhooo.com...")
console.log(hw)
console.log(decrypt(hw))输出结果C:\\Users\mysql-test>> node encrypt.js
{ iv: '61add9b0068d5d85e940ff3bba0a00e6', encryptedData:
'787ff81611b84c9ab2a55aa45e3c1d3e824e3ff583b0cb75c20b8947a4130d16' }
//加密文本
Welcome to nhooo.com... //Decrypted text