在 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.