VeloxAI
Quay lại Blog
Security· 12 phút đọc

Bảo mật API key: thiết kế lifecycle, không chỉ format

Quản lý API key an toàn với SHA-256 hashing, one-time reveal, safe rotation, audit trails và nguyên tắc least privilege.

Nguyen Son Everestt
Nguyen Son EveresttFounder & Engineering Lead, VeloxAI
#api-keys#security#auth
Bảo mật API keys
Bảo mật API keys

Một AI API key có thể tiêu tiền, truy cập dữ liệu khách hàng và kích hoạt workflows. Nhưng hầu hết platforms coi keys như passwords — generate, hash, lưu, xong. Production cần key lifecycle trải dài từ generation, storage, display, usage, rotation đến revocation.

Key format và hashing

import { createHash, randomBytes, timingSafeEqual } from "crypto";

function generateKey(env: "live" | "test") {
  const prefix = env === "live" ? "pk_live_" : "pk_test_";
  const raw = randomBytes(32).toString("base64url");
  const full = prefix + raw;
  return {
    full,                              // Show once, never log
    hash: createHash("sha256").update(full).digest("hex"), // Store
    preview: prefix + raw.slice(0, 12) + "..."              // Display
  };
}

function verify(raw: string, storedHash: string) {
  const hash = createHash("sha256").update(raw).digest("hex");
  return timingSafeEqual(Buffer.from(hash), Buffer.from(storedHash));
}
SHA-256 với timing-safe comparison

Rotation không downtime

Tạo key mới, deploy song song với key cũ (dual-running), verify key mới hoạt động, rồi revoke key cũ. Dashboard hiển thị cả hai trong transition. Làm UX rotation đủ straightforward để teams chủ động làm mỗi quý. Revocation nên soft-delete với timestamp — hard deletion phá vỡ audit trails.

Cập nhật:

Sẵn sàng dựng sản phẩm AI của bạn?

Bắt đầu free, route nhiều provider, đo chi phí và readiness trung thực ngay từ ngày đầu.