kdf.ts (1383B)
1 import { cl_crypto_error } from "./error.js"; 2 3 const DEFAULT_KDF_ITERATIONS = 210000; 4 const KDF_HASH = "SHA-256"; 5 6 export const crypto_kdf_iterations_default = (): number => DEFAULT_KDF_ITERATIONS; 7 8 export const crypto_kdf_salt_create = (length: number = 16): Uint8Array => { 9 if (!globalThis.crypto) throw new Error(cl_crypto_error.crypto_undefined); 10 const salt = new Uint8Array(length); 11 crypto.getRandomValues(salt); 12 return salt; 13 }; 14 15 export const crypto_kdf_derive_kek = async ( 16 material: Uint8Array, 17 salt: Uint8Array, 18 iterations: number 19 ): Promise<CryptoKey> => { 20 if (!globalThis.crypto || !globalThis.crypto.subtle) throw new Error(cl_crypto_error.crypto_undefined); 21 try { 22 const material_bytes = new Uint8Array(material); 23 const salt_bytes = new Uint8Array(salt); 24 const base_key = await crypto.subtle.importKey("raw", material_bytes, "PBKDF2", false, ["deriveKey"]); 25 return await crypto.subtle.deriveKey( 26 { 27 name: "PBKDF2", 28 salt: salt_bytes, 29 iterations, 30 hash: KDF_HASH 31 }, 32 base_key, 33 { 34 name: "AES-GCM", 35 length: 256 36 }, 37 false, 38 ["encrypt", "decrypt"] 39 ); 40 } catch { 41 throw new Error(cl_crypto_error.kdf_failure); 42 } 43 };