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.

JavascriptData Integrity

Code

javascriptsnippet
17 lines
// 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: false

Following 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

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.