diff --git a/blake2b.js b/blake2b.js index e94c50e..0c42be7 100644 --- a/blake2b.js +++ b/blake2b.js @@ -238,6 +238,9 @@ function blake2bInit (outlen, key, salt, personal) { if (outlen === 0 || outlen > 64) { throw new Error('Illegal output length, expected 0 < length <= 64') } + if (key && !(key instanceof Uint8Array)) { + throw new Error(`Illegal key, expected Uint8Array with 0 < length <= 64, got ${typeof key}`) + } if (key && key.length > 64) { throw new Error('Illegal key, expected Uint8Array with 0 < length <= 64') } diff --git a/blake2s.js b/blake2s.js index 517b136..39dec9b 100644 --- a/blake2s.js +++ b/blake2s.js @@ -258,6 +258,9 @@ function blake2sInit (outlen, key) { if (!(outlen > 0 && outlen <= 32)) { throw new Error('Incorrect output length, should be in [1, 32]') } + if (key && !(key instanceof Uint8Array)) { + throw new Error(`Illegal key, expected Uint8Array with 0 < length <= 32, got ${typeof key}`) + } const keylen = key ? key.length : 0 if (key && !(keylen > 0 && keylen <= 32)) { throw new Error('Incorrect key length, should be in [1, 32]') diff --git a/test_blake2b.js b/test_blake2b.js index c3069d4..e7da735 100644 --- a/test_blake2b.js +++ b/test_blake2b.js @@ -35,6 +35,23 @@ test('Input types', function (t) { t.end() }) +test('Does not accept non-Uint8 data as "key" parameter', function (t) { + t.throws(() => { + blake2bHex('The quick brown fox jumps over the lazy dog', 'aStringKey') + }, + /Illegal key, expected Uint8Array with 0 < length <= 64, got string/ + ) + + t.throws(() => { + const nonUint8Array = ['nonSensicalValue'] + blake2bHex('The quick brown fox jumps over the lazy dog', nonUint8Array) + }, + 'Illegal key, expected Uint8Array with 0 < length <= 64, got array' + ) + + t.end() +}) + test('BLAKE2b generated test vectors', function (t) { const contents = fs.readFileSync('generated_test_vectors.txt', 'utf8') contents.split('\n').forEach(function (line) { diff --git a/test_blake2s.js b/test_blake2s.js index c4ffa86..5e9d15a 100644 --- a/test_blake2s.js +++ b/test_blake2s.js @@ -70,6 +70,23 @@ function generateInput (len, seed) { return out } +test('Does not accept non-Uint8 data as "key" parameter', function (t) { + t.throws(() => { + blake2sHex('The quick brown fox jumps over the lazy dog', 'aStringKey') + }, + /Illegal key, expected Uint8Array with 0 < length <= 32, got string/ + ) + + t.throws(() => { + const nonUint8Array = ['nonSensicalValue'] + blake2sHex('The quick brown fox jumps over the lazy dog', nonUint8Array) + }, + 'Illegal key, expected Uint8Array with 0 < length <= 32, got array' + ) + + t.end() +}) + test('BLAKE2s performance', function (t) { const N = 1 << 22 // number of bytes to hash const RUNS = 3 // how often to repeat, to allow JIT to finish