const encoder = new TextEncoder(); const decoder = new TextDecoder(); function toHex(buf: ArrayBuffer | Uint8Array): string { const u8 = buf instanceof Uint8Array ? buf : new Uint8Array(buf); return [...u8].map((b) => b.toString(16).padStart(2, "0")).join(""); } function fromHex(hex: string): Uint8Array { const clean = hex.replace(/^0x/, ""); const out = new Uint8Array(clean.length / 2); for (let i = 0; i < out.length; i++) { out[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16); } return out; } export async function hashPassword(password: string): Promise { const salt = crypto.getRandomValues(new Uint8Array(16)); const key = await crypto.subtle.importKey( "raw", encoder.encode(password), "PBKDF2", false, ["deriveBits"], ); const bits = await crypto.subtle.deriveBits( { name: "PBKDF2", salt: salt as BufferSource, iterations: 120_000, hash: "SHA-256" }, key, 256, ); return `pbkdf2$${toHex(salt)}$${toHex(bits)}`; } /** ContraseƱa temporal segura (16 chars, sin ambiguos). */ export function generateSecurePassword(length = 16): string { const alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@$%*?"; const bytes = crypto.getRandomValues(new Uint8Array(length)); let out = ""; for (let i = 0; i < length; i++) out += alphabet[bytes[i]! % alphabet.length]; return out; } export async function verifyPassword(password: string, stored: string): Promise { const parts = stored.split("$"); if (parts.length !== 3 || parts[0] !== "pbkdf2") return false; const salt = fromHex(parts[1]); const expected = fromHex(parts[2]); const key = await crypto.subtle.importKey( "raw", encoder.encode(password), "PBKDF2", false, ["deriveBits"], ); const bits = new Uint8Array( await crypto.subtle.deriveBits( { name: "PBKDF2", salt: salt as BufferSource, iterations: 120_000, hash: "SHA-256" }, key, 256, ), ); if (bits.length !== expected.length) return false; let diff = 0; for (let i = 0; i < bits.length; i++) diff |= bits[i] ^ expected[i]; return diff === 0; } export async function sha256Hex(data: Uint8Array): Promise { return toHex(await crypto.subtle.digest("SHA-256", data as BufferSource)); } export { toHex, fromHex, encoder, decoder };