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, 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, 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 hmacSign(secret: string, payload: string): Promise { const key = await crypto.subtle.importKey( "raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"], ); const sig = await crypto.subtle.sign("HMAC", key, encoder.encode(payload)); return btoa(String.fromCharCode(...new Uint8Array(sig))) .replaceAll("+", "-") .replaceAll("/", "_") .replaceAll("=", ""); } export async function hmacVerify(secret: string, payload: string, sig: string): Promise { const expected = await hmacSign(secret, payload); if (expected.length !== sig.length) return false; let diff = 0; for (let i = 0; i < expected.length; i++) { diff |= expected.charCodeAt(i) ^ sig.charCodeAt(i); } return diff === 0; } export function b64urlJson(obj: unknown): string { const json = JSON.stringify(obj); return btoa(json).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", ""); } export function b64urlJsonParse(s: string): T { const pad = s.replaceAll("-", "+").replaceAll("_", "/"); const padded = pad + "=".repeat((4 - (pad.length % 4)) % 4); return JSON.parse(atob(padded)) as T; } export async function sha256Hex(data: Uint8Array): Promise { return toHex(await crypto.subtle.digest("SHA-256", data)); } export { toHex, fromHex, encoder, decoder };