Files
video-gen/video-gen-app/src/api/crypto.ts
T
2026-05-25 17:08:18 +08:00

48 lines
1.8 KiB
TypeScript

/**
* AES-256-GCM encryption/decryption for API request/response.
* Uses Web Crypto API with a shared symmetric key.
*/
const ALGO = 'AES-GCM';
const IV_LENGTH = 12;
const TAG_LENGTH = 128;
let cryptoKey: CryptoKey | null = null;
async function getCryptoKey(): Promise<CryptoKey> {
if (cryptoKey) return cryptoKey;
const keyB64 = import.meta.env.VITE_ENCRYPTION_KEY || '';
if (!keyB64) throw new Error('VITE_ENCRYPTION_KEY not configured');
let keyBytes = Uint8Array.from(atob(keyB64), c => c.charCodeAt(0));
// AES-256 requires exactly 32 bytes — pad or truncate to match backend
if (keyBytes.length !== 32) {
const padded = new Uint8Array(32);
padded.set(keyBytes.slice(0, 32));
keyBytes = padded;
}
cryptoKey = await crypto.subtle.importKey('raw', keyBytes, { name: ALGO }, false, ['encrypt', 'decrypt']);
return cryptoKey;
}
export async function encrypt(plaintext: string): Promise<string> {
const key = await getCryptoKey();
const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH));
const encoded = new TextEncoder().encode(plaintext);
const cipherBuf = await crypto.subtle.encrypt({ name: ALGO, iv, tagLength: TAG_LENGTH }, key, encoded);
const cipherBytes = new Uint8Array(cipherBuf);
// Prepend IV to ciphertext
const combined = new Uint8Array(iv.length + cipherBytes.length);
combined.set(iv);
combined.set(cipherBytes, iv.length);
return btoa(String.fromCharCode(...combined));
}
export async function decrypt(cipherB64: string): Promise<string> {
const key = await getCryptoKey();
const combined = Uint8Array.from(atob(cipherB64), c => c.charCodeAt(0));
const iv = combined.slice(0, IV_LENGTH);
const cipherBytes = combined.slice(IV_LENGTH);
const plainBuf = await crypto.subtle.decrypt({ name: ALGO, iv, tagLength: TAG_LENGTH }, key, cipherBytes);
return new TextDecoder().decode(plainBuf);
}