From 23aa85c866c69f1e2dba281571c8c588ac386bae Mon Sep 17 00:00:00 2001 From: Jonathan Underwood Date: Tue, 10 Oct 2023 21:45:05 -0700 Subject: [PATCH] Fix fromHex invalid hex behavior (#303) Co-authored-by: Daniel Cousens <413395+dcousens@users.noreply.github.com> --- AUTHORS.md | 1 + index.js | 35 ++++++++++++++++++++++++++++++--- test/node/test-buffer-badhex.js | 6 ++++++ 3 files changed, 39 insertions(+), 3 deletions(-) diff --git a/AUTHORS.md b/AUTHORS.md index 468aa19..3f4918c 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -69,5 +69,6 @@ - jkkang (jkkang@smartauth.kr) - Deklan Webster (deklanw@gmail.com) - Martin Heidegger (martin.heidegger@gmail.com) +- junderw (junderwood@bitcoinbank.co.jp) #### Generated by bin/update-authors.sh. diff --git a/index.js b/index.js index 4b441fa..8cb261d 100644 --- a/index.js +++ b/index.js @@ -860,9 +860,12 @@ function hexWrite (buf, string, offset, length) { } let i for (i = 0; i < length; ++i) { - const parsed = parseInt(string.substr(i * 2, 2), 16) - if (numberIsNaN(parsed)) return i - buf[offset + i] = parsed + const a = hexCharValueTable[string[i * 2]] + const b = hexCharValueTable[string[i * 2 + 1]] + if (a === undefined || b === undefined) { + return i + } + buf[offset + i] = a << 4 | b } return i } @@ -2114,6 +2117,32 @@ const hexSliceLookupTable = (function () { return table })() +// hex lookup table for Buffer.from(x, 'hex') +const hexCharValueTable = { + '0': 0, + '1': 1, + '2': 2, + '3': 3, + '4': 4, + '5': 5, + '6': 6, + '7': 7, + '8': 8, + '9': 9, + a: 10, + b: 11, + c: 12, + d: 13, + e: 14, + f: 15, + A: 10, + B: 11, + C: 12, + D: 13, + E: 14, + F: 15 +} + // Return not function with Error if BigInt not supported function defineBigIntMethod (fn) { return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn diff --git a/test/node/test-buffer-badhex.js b/test/node/test-buffer-badhex.js index a6388e3..486e166 100644 --- a/test/node/test-buffer-badhex.js +++ b/test/node/test-buffer-badhex.js @@ -14,6 +14,12 @@ const assert = require('assert'); assert.strictEqual(buf.write('abcdef01', 0, 'hex'), 4); assert.deepStrictEqual(buf, new Buffer([0xab, 0xcd, 0xef, 0x01])); assert.strictEqual(buf.toString('hex'), 'abcdef01'); + // Node Buffer behavior check + // > Buffer.from('abc def01','hex') + // + assert.strictEqual(buf.write('abc def01', 0, 'hex'), 1); + assert.deepStrictEqual(buf, new Buffer([0xab])); + assert.strictEqual(buf.toString('hex'), 'ab'); const copy = Buffer.from(buf.toString('hex'), 'hex'); assert.strictEqual(buf.toString('hex'), copy.toString('hex')); -- 2.34.1