`title: WebCrypto PBKDF2 密钥派生与加密持久化``categories: Web 开发/前端/数据管理``keywords: WebCrypto,PBKDF2,派生密钥,AES-GCM,加密,IndexedDB,OPFS``description: 基于密码与盐使用 PBKDF2 派生密钥并执行 AES-GCM 加密,将密文与元数据持久化到 IndexedDB 或 OPFS,兼顾安全与可用性。`派生与加密async function deriveKey(password, salt) {
const base = await crypto.subtle.importKey('raw', new TextEncoder().encode(password), 'PBKDF2', false, ['deriveKey']);
return crypto.subtle.deriveKey({ name: 'PBKDF2', salt, iterations: 100000, hash: 'SHA-256' }, base, { name: 'AES-GCM', length: 256 }, true, ['encrypt','decrypt']);
}
async function encryptWithPBKDF2(password, data) {
const salt = crypto.getRandomValues(new Uint8Array(16));
const key = await deriveKey(password, salt);
const iv = crypto.getRandomValues(new Uint8Array(12));
const cipher = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, data);
return { salt, iv, cipher: new Uint8Array(cipher) };
}

发表评论 取消回复