1'use strict'; 2const common = require('../common'); 3if (!common.hasCrypto) 4 common.skip('missing crypto'); 5 6const assert = require('assert'); 7const crypto = require('crypto'); 8 9// 'should consider equal strings to be equal' 10assert.strictEqual( 11 crypto.timingSafeEqual(Buffer.from('foo'), Buffer.from('foo')), 12 true 13); 14 15// 'should consider unequal strings to be unequal' 16assert.strictEqual( 17 crypto.timingSafeEqual(Buffer.from('foo'), Buffer.from('bar')), 18 false 19); 20 21{ 22 // Test TypedArrays with different lengths but equal byteLengths. 23 const buf = crypto.randomBytes(16).buffer; 24 const a1 = new Uint8Array(buf); 25 const a2 = new Uint16Array(buf); 26 const a3 = new Uint32Array(buf); 27 28 for (const left of [a1, a2, a3]) { 29 for (const right of [a1, a2, a3]) { 30 assert.strictEqual(crypto.timingSafeEqual(left, right), true); 31 } 32 } 33} 34 35assert.throws( 36 () => crypto.timingSafeEqual(Buffer.from([1, 2, 3]), Buffer.from([1, 2])), 37 { 38 code: 'ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH', 39 name: 'RangeError', 40 message: 'Input buffers must have the same byte length' 41 } 42); 43 44assert.throws( 45 () => crypto.timingSafeEqual('not a buffer', Buffer.from([1, 2])), 46 { 47 code: 'ERR_INVALID_ARG_TYPE', 48 name: 'TypeError', 49 message: 50 'The "buf1" argument must be an instance of Buffer, TypedArray, or ' + 51 'DataView.' 52 } 53); 54 55assert.throws( 56 () => crypto.timingSafeEqual(Buffer.from([1, 2]), 'not a buffer'), 57 { 58 code: 'ERR_INVALID_ARG_TYPE', 59 name: 'TypeError', 60 message: 61 'The "buf2" argument must be an instance of Buffer, TypedArray, or ' + 62 'DataView.' 63 } 64); 65