資料加密
規則
- TLS 無所不在:將 HTTP 重新導向至 HTTPS、設定 HSTS 標頭,絕不允許未加密連線
- 在應用程式層級以 AES-256-GCM 加密 PII 資料欄位,再存入資料庫
- 電子郵件以 SHA-256 雜湊供查詢使用,以 AES-256-GCM 加密供顯示使用——在不會暴露資料的前提下支援搜尋
- 密碼:僅使用 bcrypt 或 argon2id——絕不使用 SHA、MD5 或可逆加密
- 加密資料庫備份,並將加密金鑰與資料分開存放
- 瀏覽器端加密使用
crypto.subtle,伺服器端使用 node:crypto
- 將加密金鑰存放於機密管理服務,切勿寫在程式碼中或與加密資料放在一起
import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
const ENCRYPTION_KEY = Buffer.from(process.env.ENCRYPTION_KEY!, "hex");
function encrypt(plaintext: string): string {
const iv = randomBytes(12);
const cipher = createCipheriv("aes-256-gcm", ENCRYPTION_KEY, iv);
const encrypted = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
const tag = cipher.getAuthTag();
return Buffer.concat([iv, tag, encrypted]).toString("base64");
}
function decrypt(ciphertext: string): string {
const buf = Buffer.from(ciphertext, "base64");
const iv = buf.subarray(0, 12);
const tag = buf.subarray(12, 28);
const encrypted = buf.subarray(28);
const decipher = createDecipheriv("aes-256-gcm", ENCRYPTION_KEY, iv);
decipher.setAuthTag(tag);
return decipher.update(encrypted) + decipher.final("utf8");
}
應避免事項
- 以明文儲存 PII——一次資料庫外洩就會暴露一切
- 使用 ECB 模式或未經認證的 AES(無 HMAC 的 CBC)——請使用 GCM
- 使用 MD5 或 SHA 進行密碼雜湊——它們並非密碼雜湊演算法
- 在原始碼中硬編碼加密金鑰——請使用環境變數或 KMS
- 透過 HTTP 傳送敏感資料,即使只在內部網路也一樣——所有連線都應使用 TLS