2.7 KiB
Hex encoding
(no submodules)
Purpose
Convert between Uint8Array byte buffers and lowercase hexadecimal strings. Hex is the canonical human-readable representation of cryptographic material (digests, public keys, nonces) because every byte maps to exactly two characters with no ambiguity or padding. This module re-exports bytesToHex and hexToBytes from @suaveplan/bytes under the crypto-friendly names toHex / fromHex, ensuring every @suaveplan/crypto-* package produces byte-for-byte identical output and rejects malformed input with a stable error code.
Features
toHex(bytes)— lowercase, no0xprefix; delegates to@suaveplan/bytes.fromHex(hex)— accepts both upper and lower case; rejects odd length or non-hex characters.- Throws
BytesError(BYTES.ENCODE.INVALID_HEX)on malformed input (from@suaveplan/bytes). - Zero implementation code in this module — pure delegation ensures a single source of truth.
Usage: Basic Example
import { fromHex, toHex } from "@suaveplan/crypto-utils/encoding";
const digest = new Uint8Array([0xde, 0xad, 0xbe, 0xef]);
const s = toHex(digest); // "deadbeef"
const back = fromHex(s); // Uint8Array([0xde, 0xad, 0xbe, 0xef])
Usage: Advanced Example
import { fromHex, toHex } from "@suaveplan/crypto-utils/encoding";
import { BytesError } from "@suaveplan/bytes";
function parseDigest(input: string): Uint8Array {
try {
return fromHex(input.trim().replace(/^0x/, ""));
} catch (err) {
if (err instanceof BytesError) {
throw new Error(`digest must be hex-encoded: ${input.slice(0, 32)}`);
}
throw err;
}
}
const digest = parseDigest("0xDEADBEEF");
console.log(toHex(digest));
API Reference
toHex(bytes: Uint8Array): string— Returns a lowercase hex string whose length is2 * bytes.length. Never throws. Alias forbytesToHexfrom@suaveplan/bytes.fromHex(hex: string): Uint8Array— Parses upper or lower case. ThrowsBytesErrorwith codeBYTES.ENCODE.INVALID_HEXon odd-length or non-hex input. Alias forhexToBytesfrom@suaveplan/bytes.
Implementation Notes
This module is a thin delegation layer: toHex and fromHex are direct const aliases for bytesToHex and hexToBytes from @suaveplan/bytes. No encoding logic lives here — this removes duplication between the two packages and ensures all @suaveplan/crypto-* consumers share exactly the same implementation. Errors thrown on invalid input originate from @suaveplan/bytes as BytesError instances; callers should catch BytesError rather than the old CryptoUtilsError. The public function names (toHex / fromHex) are preserved so no downstream caller requires import changes.