示例工程 39-secrets-safestorage
39-secrets-safestorage/app/shared/crypto.ts
import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
export type EncryptedValue = {
ciphertext: string;
iv: string;
tag: string;
};
export function generateDataKey(): Buffer {
return randomBytes(32);
}
export function encryptSecret(
dataKey: Buffer,
plaintext: string,
): EncryptedValue {
const iv = randomBytes(12);
const cipher = createCipheriv("aes-256-gcm", dataKey, iv);
const ciphertext = Buffer.concat([
cipher.update(plaintext, "utf8"),
cipher.final(),
]);
const tag = cipher.getAuthTag();
return {
ciphertext: ciphertext.toString("base64"),
iv: iv.toString("base64"),
tag: tag.toString("base64"),
};
}
export function decryptSecret(dataKey: Buffer, value: EncryptedValue): string {
const decipher = createDecipheriv(
"aes-256-gcm",
dataKey,
Buffer.from(value.iv, "base64"),
);
decipher.setAuthTag(Buffer.from(value.tag, "base64"));
const plaintext = Buffer.concat([
decipher.update(Buffer.from(value.ciphertext, "base64")),
decipher.final(),
]);
return plaintext.toString("utf8");
}
export function tamperCiphertext(value: EncryptedValue): EncryptedValue {
const bytes = Buffer.from(value.ciphertext, "base64");
if (bytes.length === 0) return { ...value, ciphertext: "AA==" };
bytes[bytes.length - 1] = (bytes[bytes.length - 1] ?? 0) ^ 0xff;
return { ...value, ciphertext: bytes.toString("base64") };
}
export function maskSecret(value: string): string {
if (value.length === 0) return "(empty)";
if (value.length <= 4) return "•".repeat(value.length);
return `${value.slice(0, 2)}${"•".repeat(Math.min(10, value.length - 4))}${value.slice(-2)}`;
}
export function ciphertextBytes(value: EncryptedValue): number {
return (
Buffer.from(value.ciphertext, "base64").length +
Buffer.from(value.iv, "base64").length +
Buffer.from(value.tag, "base64").length
);
}