3.2 KiB
Base64 encoding
(no submodules)
Purpose
Standard Base64 (RFC 4648 §4) and URL-safe Base64 (§5) encoding and decoding for byte buffers. Standard Base64 is the default for JSON, JWT headers, and binary payloads in MIME. URL-safe Base64 substitutes - and _ for + and / so the result can appear in URLs and file paths without percent-escaping. Standard Base64 (toBase64 / fromBase64) is delegated entirely to @suaveplan/bytes; the URL-safe variants are implemented here because they use a crypto-specific +→- / →_ substitution pattern not present in the bytes package.
Features
toBase64/fromBase64: RFC 4648 §4 with=padding — delegated to@suaveplan/bytes.toBase64Url/fromBase64Url: RFC 4648 §5 without padding — implemented natively by post-processing the standard base64 output.- URL-safe decoder tolerates optional trailing
=padding. - Throws
BytesError(from@suaveplan/bytes) on malformed standard base64; same error type propagates through the URL-safe decoder.
Usage: Basic Example
import { fromBase64, toBase64 } from "@suaveplan/crypto-utils/encoding";
const s = toBase64(new TextEncoder().encode("foobar")); // "Zm9vYmFy"
const bytes = fromBase64(s);
Usage: Advanced Example
import { fromBase64Url, toBase64Url } from "@suaveplan/crypto-utils/encoding";
import { BytesError } from "@suaveplan/bytes";
function parseJwtSegment(segment: string): Uint8Array {
try {
return fromBase64Url(segment);
} catch (err) {
if (err instanceof BytesError) {
throw new Error(`JWT segment not valid base64url: ${segment.slice(0, 8)}…`);
}
throw err;
}
}
const encoded = toBase64Url(new Uint8Array([0xfb, 0xff, 0xbf]));
parseJwtSegment(encoded);
API Reference
toBase64(bytes: Uint8Array): string— RFC 4648 §4 with=padding. Never throws. Alias forbytesToBase64from@suaveplan/bytes.fromBase64(s: string): Uint8Array— RFC 4648 §4. ThrowsBytesError(BYTES.ENCODE.INVALID_BASE64)on invalid characters or bad length.toBase64Url(bytes: Uint8Array): string— RFC 4648 §5 without padding. CallstoBase64then substitutes+→-,/→_, strips=.fromBase64Url(s: string): Uint8Array— RFC 4648 §5. Restores+and/, adds padding, then delegates tofromBase64. Tolerates optional trailing=padding. ThrowsBytesErroron malformed input.
Implementation Notes
Standard base64 (toBase64 / fromBase64) are direct const aliases for bytesToBase64 / base64ToBytes from @suaveplan/bytes, eliminating duplicate encoding logic. URL-safe base64 is implemented as a post-processing step: toBase64Url calls toBase64 then performs three String.replace calls to swap characters and strip padding. fromBase64Url reverses the substitution, computes missing padding (aligning to a multiple of 4), then delegates to fromBase64. This approach ensures the URL-safe round-trip shares exactly the same underlying byte semantics as the standard variant. Error type for invalid input is BytesError (from @suaveplan/bytes) rather than the legacy CryptoUtilsError.