Panduan Full Stack & AI Application Engineer: Web Crypto API di Sisi Klien — Mengamankan API Key Lokal dengan PBKDF2 & AES-GCM

Spesialisasi Rekayasa Perangkat Lunak: Ditulis oleh Aldian Fazrihady — Senior Cloud Engineer, GCP Professional Cloud Architect, GCP Professional Data Engineer, Backend Engineer, AI Application Engineer & Full Stack Engineer.

1. Bahaya Menyimpan API Key LLM (OpenAI / Gemini / Anthropic) dalam Plaintext di localStorage

Pada aplikasi AI Bring-Your-Own-Key (BYOK) dan PWA lokal yang dibangun oleh AI Application Engineer dan Full Stack Engineer, menyimpan kredensial API secara terbuka di localStorage atau IndexedDB membuat kunci rentan dicuri oleh skrip pihak ketiga. Solusi standarnya adalah mengenkripsi kunci di memori browser menggunakan Web Crypto API (window.crypto.subtle).

2. Derivasi Kunci PBKDF2 (SHA-256) dan Enkripsi Terautentikasi AES-GCM 256-Bit

Dengan menurunkan kunci kriptografi non-ekstraktable (extractable: false) menggunakan crypto.subtle.deriveKey berbasis PBKDF2 serta mengenkripsi payload dengan AES-GCM dan Initialization Vector (IV) 12-byte acak per operasi, ciphertext tetap aman meskipun penyimpanan lokal diakses. Berikut adalah kode produksi lengkapnya:

async function deriveKey(passphrase: string, salt: Uint8Array): Promise<CryptoKey> {
  const enc = new TextEncoder();
  const keyMaterial = await window.crypto.subtle.importKey(
    "raw",
    enc.encode(passphrase),
    { name: "PBKDF2" },
    false,
    ["deriveBits", "deriveKey"]
  );

  return window.crypto.subtle.deriveKey(
    {
      name: "PBKDF2",
      salt: salt,
      iterations: 100000,
      hash: "SHA-256",
    },
    keyMaterial,
    { name: "AES-GCM", length: 256 },
    false,
    ["encrypt", "decrypt"]
  );
}
export async function encryptText(text: string, passphrase: string): Promise<string> {
  if (!text) return "";
  const salt = window.crypto.getRandomValues(new Uint8Array(16));
  const iv = window.crypto.getRandomValues(new Uint8Array(12));
  const key = await deriveKey(passphrase, salt);
  const enc = new TextEncoder();
  
  const ciphertextBuffer = await window.crypto.subtle.encrypt(
    { name: "AES-GCM", iv: iv },
    key,
    enc.encode(text)
  );

  const payload = {
    salt: arrayBufferToBase64(salt),
    iv: arrayBufferToBase64(iv),
    ciphertext: arrayBufferToBase64(ciphertextBuffer),
  };

  return JSON.stringify(payload);
}
useEffect(() => {
  const hasVerify = typeof window !== "undefined" && !!localStorage.getItem("passphrase_verify");
  if (hasVerify) {
    setIsLocked(true);
  } else {
    // Populate raw keys directly if no vault is set
    setOpenaiKey(localStorage.getItem("openai_api_key") || "");
    // ... other keys
  }
}, []);
const preventCopyPasteActions = {
  onCopy: (e: React.ClipboardEvent) => e.preventDefault(),
  onCut: (e: React.ClipboardEvent) => e.preventDefault(),
  onDragStart: (e: React.DragEvent) => e.preventDefault(),
  onContextMenu: (e: React.MouseEvent) => e.preventDefault(),
  onKeyDown: (e: React.KeyboardEvent) => {
    if ((e.ctrlKey || e.metaKey) && (e.key === "c" || e.key === "x")) {
      e.preventDefault();
    }
  }
};

Ringkasan Arsitektur Produksi & Praktik Terbaik (Checklist Teknis)


About the Author — Hire Aldian Fazrihady (Cloud Engineer, GCP Professional Cloud Architect, GCP Professional Data Engineer, Backend, AI & Full Stack Engineer)

Aldian Fazrihady is a Top-Rated Senior Cloud Engineer, GCP Professional Cloud Architect (Google Cloud Certified), GCP Professional Data Engineer (Google Cloud Certified), Backend Engineer (Python, Django, FastAPI, Go, PostgreSQL), AI Application Engineer (LLMs, RAG, MCP, Google ADK, LangGraph), and Full Stack Engineer (React, Next.js, TypeScript) with 15+ years of production software engineering experience.

Hire Aldian Fazrihady on Upwork | Book 1-Day Programming Service ($100 USD / Rp 1.000.000) | View Live AI Portfolio | Send a Direct Message

Related Engineering Articles

Engineering Role Pillar Guides & Category Hubs