From 588b388181b2884a3f7197c462227ce05c4c2358 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobias=20Nie=C3=9Fen?= Date: Tue, 9 Oct 2018 09:36:46 +1100 Subject: [PATCH] crypto: use byteLength in timingSafeEqual PR-URL: https://github.com/nodejs/node/pull/29657 Co-authored-by: ZaneHannanAU Co-authored-by: Rich Trott Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: Ben Noordhuis Reviewed-By: Sam Roberts Reviewed-By: Ruben Bridgewater Reviewed-By: Luigi Pinca Reviewed-By: Minwoo Jung --- lib/internal/crypto/util.js | 2 +- lib/internal/errors.js | 2 +- test/sequential/test-crypto-timing-safe-equal.js | 16 +++++++++++++++- 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/lib/internal/crypto/util.js b/lib/internal/crypto/util.js index ddef1a163ceec2..544d44669ae466 100644 --- a/lib/internal/crypto/util.js +++ b/lib/internal/crypto/util.js @@ -78,7 +78,7 @@ function timingSafeEqual(buf1, buf2) { throw new ERR_INVALID_ARG_TYPE('buf2', ['Buffer', 'TypedArray', 'DataView'], buf2); } - if (buf1.length !== buf2.length) { + if (buf1.byteLength !== buf2.byteLength) { throw new ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH(); } return _timingSafeEqual(buf1, buf2); diff --git a/lib/internal/errors.js b/lib/internal/errors.js index eff688e6f5fc07..8412c710c9c06c 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -750,7 +750,7 @@ E('ERR_CRYPTO_SCRYPT_NOT_SUPPORTED', 'Scrypt algorithm not supported', Error); // Switch to TypeError. The current implementation does not seem right. E('ERR_CRYPTO_SIGN_KEY_REQUIRED', 'No key provided to sign', Error); E('ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH', - 'Input buffers must have the same length', RangeError); + 'Input buffers must have the same byte length', RangeError); E('ERR_DNS_SET_SERVERS_FAILED', 'c-ares failed to set servers: "%s" [%s]', Error); E('ERR_DOMAIN_CALLBACK_NOT_AVAILABLE', diff --git a/test/sequential/test-crypto-timing-safe-equal.js b/test/sequential/test-crypto-timing-safe-equal.js index dcebef29d782b0..75385e5f88ad50 100644 --- a/test/sequential/test-crypto-timing-safe-equal.js +++ b/test/sequential/test-crypto-timing-safe-equal.js @@ -18,12 +18,26 @@ assert.strictEqual( false ); +{ + // Test TypedArrays with different lengths but equal byteLengths. + const buf = crypto.randomBytes(16).buffer; + const a1 = new Uint8Array(buf); + const a2 = new Uint16Array(buf); + const a3 = new Uint32Array(buf); + + for (const left of [a1, a2, a3]) { + for (const right of [a1, a2, a3]) { + assert.strictEqual(crypto.timingSafeEqual(left, right), true); + } + } +} + common.expectsError( () => crypto.timingSafeEqual(Buffer.from([1, 2, 3]), Buffer.from([1, 2])), { code: 'ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH', type: RangeError, - message: 'Input buffers must have the same length' + message: 'Input buffers must have the same byte length' } );