在 NodeJS 中加密和解密数据


NodeJS 提供了内置库 crypto 来在 NodeJS 中加密和解密数据。我们可以使用此库加密任何类型的数据。你可以对一个字符串、一个缓冲区,甚至一个数据流执行加密操作。crypto 也包含多种用于加密的算法。请查看官方资源了解相同的信息。本文中,我们将使用最流行的 AES (高级加密标准) 进行加密。

配置“crypto”依赖项

  • 在你的项目中,检查 NodeJS 是否已初始化。如果没有,请使用以下命令初始化 NodeJS。

>> npm init -y
  • 在手动安装 Node.js 时会自动添加“crypto”库。如果没有,可以使用以下命令来安装 crypto。

>> npm install crypto –save

示例

加密和解密数据

//Checking the crypto module
const crypto = require('crypto');
const algorithm = 'aes-256-cbc'; //Using AES encryption
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);

//Encrypting text
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') };
}

// Decrypting text
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();
}

// Text send to encrypt function
var hw = encrypt("Welcome to Tutorials Point...")
console.log(hw)
console.log(decrypt(hw))

输出

C:\Users\mysql-test>> node encrypt.js
{ iv: '61add9b0068d5d85e940ff3bba0a00e6', encryptedData:
'787ff81611b84c9ab2a55aa45e3c1d3e824e3ff583b0cb75c20b8947a4130d16' }
//Encrypted text
Welcome to Tutorials Point... //Decrypted text

更新于:12-Sep-2023

4.6K+ 浏览量

开启你的 事业

通过完成课程获得认证

开始学习
广告
© . All rights reserved.