Node.js Crypto:對稱與非對稱加密 (AES 與 RSA) 實戰

在 Node.js 中處理敏感資料(如信用卡資訊、身份識別、通訊內容)時,單純的雜湊是不夠的。我們需要確保資料能被加密(Encryption)保護,且僅能由持有正確金鑰的人進行解密(Decryption)。

1. 對稱加密 (Symmetric Encryption)

對稱加密使用「同一把金鑰」進行加解密。

  • 優點:效能極高,適合加密大型檔案或大量資料流。
  • 缺點:如果金鑰在傳輸過程中洩漏,加密將形同虛設。

推薦演算法:AES-256-GCM

AES-256-GCM 是目前的黃金標準,它不僅提供加密,還包含 認證標籤 (Auth Tag),能偵測資料是否在加密狀態下被竄改。

const crypto = require('crypto');

const algorithm = 'aes-256-gcm';
const key = crypto.randomBytes(32); // 產生 256 位元密鑰
const iv = crypto.randomBytes(12); // 初始化向量

// 加密函式
function encrypt(text) {
  const cipher = crypto.createCipheriv(algorithm, key, iv);
  let encrypted = cipher.update(text, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  const authTag = cipher.getAuthTag().toString('hex');
  return { encrypted, authTag };
}

// 解密函式
function decrypt(encrypted, authTag) {
  const decipher = crypto.createDecipheriv(algorithm, key, iv);
  decipher.setAuthTag(Buffer.from(authTag, 'hex'));
  let decrypted = decipher.update(encrypted, 'hex', 'utf8');
  decrypted += decipher.final('utf8');
  return decrypted;
}

const secret = '這是不可告人的機密資訊';
const result = encrypt(secret);
console.log('解密成功:', decrypt(result.encrypted, result.authTag));

2. 非對稱加密 (Asymmetric Encryption)

非對稱加密使用一對金鑰:

  • 公鑰 (Public Key):公開給任何人。用於加密
  • 私鑰 (Private Key):由本人嚴密保管。用於解密

核心場景:數位簽章 (Digital Signature)

除了加密,非對稱加密常用於證明身份。如果你用私鑰對合約「簽署」,任何人都可以拿你的公鑰來「驗證」這份文件確實是你簽發的。

// RSA 加解密範例 (簡化版)
const { publicEncrypt, privateDecrypt, generateKeyPairSync } = require('crypto');

// 產生密鑰對
const { publicKey, privateKey } = generateKeyPairSync('rsa', {
  modulusLength: 2048,
});

const secretData = Buffer.from('我的銀行密碼');

// 用公鑰加密
const encrypted = publicEncrypt(publicKey, secretData);

// 只有持私鑰的人能解密
const decrypted = privateDecrypt(privateKey, encrypted);
console.log('解出原始資料:', decrypted.toString());

二者結合:混合加密

在實際的 HTTPS 通訊中,通常會結合這兩者:

  1. 使用 非對稱加密 安全地傳遞一把臨時的「對稱金鑰」。
  2. 後續的大量資料傳輸,全部改用 對稱加密 以追求極致效能。
安全警示:永遠不要將金鑰(Secret Keys)寫死在原始碼中。請務必使用 環境變數 (Environment Variables) 進行管理,防止程式碼上傳至 GitHub 時洩漏。

總結

  1. AES-256-GCM 是對稱加密的首選,記得 IV 不能重複。
  2. RSA 適用於身份驗證與小量關鍵金鑰的分發。
  3. 務必理解 私鑰 (Private Key) 的安全性等級等同於你的整套系統安全。