export function simpleHash(s: string): number { let hash = 0, i, chr; if (s.length === 0) return hash; for (i = 0; i < s.length; i++) { chr = s.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; } export function base64Decode(s: string): Uint8Array { const binString = atob(s); const len = binString.length; const bytes = new Uint8Array(len); for (let i = 0; i < len; i++) { bytes[i] = binString.charCodeAt(i); } return bytes; } export function base64Encode(buffer: Uint8Array | string): string { if (typeof buffer === "string") { buffer = new TextEncoder().encode(buffer); } let binary = ""; const len = buffer.byteLength; for (let i = 0; i < len; i++) { binary += String.fromCharCode(buffer[i]); } return btoa(binary); } export function base64EncodedDataUrl( mimeType: string, buffer: Uint8Array, ): string { return `data:${mimeType};base64,${base64Encode(buffer)}`; } export function base64DecodeDataUrl(dataUrl: string): Uint8Array { const b64Encoded = dataUrl.split(",", 2)[1]; return base64Decode(b64Encoded); } /** * Perform sha256 hash using the browser's crypto APIs * Note: this will only work over HTTPS * @param message */ export async function hashSHA256(message: string): Promise { // Transform the string into an ArrayBuffer const encoder = new TextEncoder(); const data = encoder.encode(message); // Generate the hash const hashBuffer = await globalThis.crypto.subtle.digest("SHA-256", data); // Transform the hash into a hex string return Array.from(new Uint8Array(hashBuffer)).map((b) => b.toString(16).padStart(2, "0") ).join(""); }