mirror of
https://github.com/profullstack/logicsrc.git
synced 2026-12-01 01:14:47 +00:00
fix(ans): reject non-hex input in fromHex instead of silently decoding to 0 (#91)
Some checks failed
CI / build (push) Has been cancelled
test / test (push) Has been cancelled
Some checks failed
CI / build (push) Has been cancelled
test / test (push) Has been cancelled
fromHex validated only that the string was even-length, then used
parseInt(pair, 16) per byte. parseInt returns NaN for a non-hex pair, and a
Uint8Array stores NaN as 0 — so fromHex('zzzz') silently returned [0, 0]
instead of failing. Add a hex-charset check (allowing empty input) so bad
input throws. Add bytes.test.ts covering valid decode, round-trip, odd-length
and non-hex cases.
This commit is contained in:
parent
7d62e3b661
commit
8107140228
2 changed files with 30 additions and 0 deletions
|
|
@ -26,6 +26,9 @@ export function toHex(bytes: Uint8Array): string {
|
|||
export function fromHex(hex: string): Uint8Array {
|
||||
const clean = hex.startsWith('0x') ? hex.slice(2) : hex;
|
||||
if (clean.length % 2 !== 0) throw new Error('odd-length hex string');
|
||||
// Reject non-hex input. Without this, parseInt returns NaN for a bad pair
|
||||
// and the Uint8Array silently stores 0, producing wrong bytes.
|
||||
if (!/^[0-9a-fA-F]*$/.test(clean)) throw new Error('invalid hex string');
|
||||
const out = new Uint8Array(clean.length / 2);
|
||||
for (let i = 0; i < out.length; i++) out[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);
|
||||
return out;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue