SPB Git

Repository Public

base64url.ts 1.1 KB 19 lines typescript

1// base64url (RFC 4648 §5, no padding) <-> bytes. WebAuthn JSON uses this encoding for every binary field.23export function bytesToBase64url(input: ArrayBuffer | ArrayBufferView): string {4  const bytes = input instanceof ArrayBuffer ? new Uint8Array(input) : new Uint8Array(input.buffer, input.byteOffset, input.byteLength);5  let bin = "";6  for (let i = 0; i < bytes.length; i += 0x8000) bin += String.fromCharCode(...bytes.subarray(i, i + 0x8000));7  return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");8}910export function base64urlToBytes(value: string): Uint8Array<ArrayBuffer> {11  if (!/^[A-Za-z0-9_-]*={0,2}$/.test(value) && !/^[A-Za-z0-9+/]*={0,2}$/.test(value)) throw new TypeError("invalid base64url");12  const clean = value.replace(/=+$/, "").replace(/-/g, "+").replace(/_/g, "/");13  if (clean.length % 4 === 1) throw new TypeError("invalid base64url length");14  const bin = atob(clean + "=".repeat((4 - (clean.length % 4)) % 4));15  const out = new Uint8Array(new ArrayBuffer(bin.length));16  for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);17  return out;18}19
Files main
Menu

Theme