import { SERVER_KEYS_CODES, ServerKeysError, } from "../../error-codes/error-codes.js"; /** Encode a byte array as a lowercase hex string (no separators). */ export function bytesToHex(bytes: Uint8Array): string { let out = ""; for (const byte of bytes) out += byte.toString(16).padStart(2, "0"); return out; } /** * Decode a lowercase or uppercase hex string into a `Uint8Array`. Throws * `ServerKeysError(SERVER_KEYS_INVALID_INPUT)` on odd length or non-hex * characters. Used by the license sub-commands to deserialise the * `signingKey` / `publicKey` fields of the `LicenseKeypairFile` JSON * envelope. */ export function hexToBytes(hex: string): Uint8Array { if (hex.length % 2 !== 0) { throw new ServerKeysError( SERVER_KEYS_CODES.INVALID_INPUT, "Hex string length must be even" ); } const out = new Uint8Array(hex.length / 2); for (let i = 0; i < out.length; i++) { const start = i * 2; const slice = hex.slice(start, start + 2); if (!/^[0-9a-fA-F]{2}$/.test(slice)) { throw new ServerKeysError( SERVER_KEYS_CODES.INVALID_INPUT, `Invalid hex byte "${slice}" at offset ${start}` ); } out[i] = Number.parseInt(slice, 16); } return out; }