示例工程 39-secrets-safestorage

39-secrets-safestorage/demo-01-envelope/envelope.ts

typescript · 2.1 KB

import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";

type Encrypted = { ciphertext: string; iv: string; tag: string };

function encrypt(key: Buffer, plaintext: string): Encrypted {
  const iv = randomBytes(12);
  const cipher = createCipheriv("aes-256-gcm", key, iv);
  const ciphertext = Buffer.concat([
    cipher.update(plaintext, "utf8"),
    cipher.final(),
  ]);
  return {
    ciphertext: ciphertext.toString("base64"),
    iv: iv.toString("base64"),
    tag: cipher.getAuthTag().toString("base64"),
  };
}

function decrypt(key: Buffer, value: Encrypted): string {
  const decipher = createDecipheriv(
    "aes-256-gcm",
    key,
    Buffer.from(value.iv, "base64"),
  );
  decipher.setAuthTag(Buffer.from(value.tag, "base64"));
  return Buffer.concat([
    decipher.update(Buffer.from(value.ciphertext, "base64")),
    decipher.final(),
  ]).toString("utf8");
}

const key = randomBytes(32);
const plaintext = "sk-demo-envelope-0000000000000000";
const first = encrypt(key, plaintext);
const second = encrypt(key, plaintext);
const decrypted = decrypt(key, first);
const ivUnique = first.iv !== second.iv;
const ciphertextUnique = first.ciphertext !== second.ciphertext;

const bad = Buffer.from(first.ciphertext, "base64");
bad[bad.length - 1] = (bad[bad.length - 1] ?? 0) ^ 0xff;
let tamperError = "";
try {
  decrypt(key, { ...first, ciphertext: bad.toString("base64") });
} catch (error) {
  tamperError = error instanceof Error ? error.message : String(error);
}

const nextKey = randomBytes(32);
const rotated = encrypt(nextKey, decrypted);
const rotatedBack = decrypt(nextKey, rotated);
let oldKeyFails = false;
try {
  decrypt(key, rotated);
} catch {
  oldKeyFails = true;
}

const ok =
  decrypted === plaintext &&
  ivUnique &&
  ciphertextUnique &&
  tamperError.length > 0 &&
  rotatedBack === plaintext &&
  oldKeyFails;

console.log(
  JSON.stringify({
    evt: "smoke",
    ok,
    plaintextLength: plaintext.length,
    cipherBytes: Buffer.from(first.ciphertext, "base64").length,
    ivUnique,
    ciphertextUnique,
    tamperError,
    rotatedBack,
    oldKeyFails,
  }),
);