Buffer.from Hex Stops At The First Invalid Pair
Buffer.from(value, "hex") silently stops at the first invalid character pair instead of throwing; untrusted hex must be shape-checked first.
Code
// Buffer.from(data, 'hex') parses leading valid byte pairs and silently
// stops at the first invalid character pair — no error is thrown.
console.log('valid:', Buffer.from('48656c6c6f', 'hex').toString());
console.log('invalid zz:', JSON.stringify(Buffer.from('zz', 'hex').toString()), 'length:', Buffer.from('zz', 'hex').length);
console.log('mixed 48zz6c:', JSON.stringify(Buffer.from('48zz6c', 'hex').toString()));
console.log('odd tail 486:', JSON.stringify(Buffer.from('486', 'hex').toString()), 'length:', Buffer.from('486', 'hex').length);
// For untrusted input, validate the shape before decoding: a strict regex
// plus an even-length check catches corruption the decoder glosses over.
const looksHex = (value) => /^[0-9a-f]+$/i.test(value) && value.length % 2 === 0;
console.log('checksum ok:', looksHex('48656c6c6f'), 'rejected:', looksHex('48zz'));
// Re-encoding the decoded bytes round-trips only when the input was fully
// valid, which makes the silent truncation visible in tests.
const reencoded = Buffer.from('48656c6c6fzz', 'hex').toString('hex');
console.log('re-encoded:', reencoded, 'round-trips:', reencoded === '48656c6c6fzz');Output
Captured from a sandboxed run of this snippet in the build pipeline.
valid: Hello
invalid zz: "" length: 0
mixed 48zz6c: "H"
odd tail 486: "H" length: 1
checksum ok: true rejected: false
re-encoded: 48656c6c6f round-trips: falseFollowing the execution — Buffer.from Hex Stops At The First Invalid Pair
The code’s whole job belongs to the function looksHex.
What to watch for
- The environment needs no preparation beyond having the interpreter or compiler.
Putting it to use
Entry signature: const looksHex = (value)
The run emits 6 labeled sections — valid:, invalid zz:, mixed 48zz6c:, odd tail 486:, checksum ok:, re-encoded: — one per step.
Core lines
const looksHex = (value) => /^[0-9a-f]+$/i.test(value) && value.length % 2 === 0;
Interactive Tools for This Topic
Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.CSS Color ConverterConvert colors between HEX, rgb(), and hsl() instantly, with support for shorthand hex and rgb or hsl inputs. Fully offline and dependency free.Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.RGBA / Hex Color ConverterConvert colors between #RRGGBB, #RRGGBBAA, rgb(), and rgba() forms with alpha handling and validation.
FAQ
- Are there third-party dependencies?
- No. The dependency list is empty; the code stays inside the standard library. The file defines `looksHex` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.