← 中文资源

简体中文版本

Buffer.from 的 hex 在首个非法对处静默截断

Buffer.from(x, 'hex') 解析到第一对非法字符就静默停下,不抛错:'48zz6c' 只得到 'H',奇数尾巴也被丢掉;不可信输入先用严格正则加偶数长度校验再解码。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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

实现说明

活动部件是函数 looksHex。

使用要点

  • 直接运行文件,输出会带上标签,比如 valid:、invalid zz:、mixed 48zz6c:——输出的每一行都能指回产生它的那次调用。

常见问题

有第三方依赖吗?

没有。依赖清单是空的,代码只用标准库。 文件在加载时定义 looksHex。

入口签名:const looksHex = (value)

核心语句

const looksHex = (value) => /^[0-9a-f]+$/i.test(value) && value.length % 2 === 0;

代码示例

// 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');