0
0
mirror of https://github.com/nodejs/node.git synced 2024-11-21 21:19:50 +01:00
nodejs/test/parallel/test-crypto-oneshot-hash.js
Joyee Cheung 4c46439fe9 crypto: implement crypto.hash()
This patch introduces a helper crypto.hash() that computes
a digest from the input at one shot. This can be 1.2-1.6x faster
than the object-based createHash() for smaller inputs (<= 5MB)
that are readily available (not streamed) and incur less memory
overhead since no intermediate objects will be created.

PR-URL: https://github.com/nodejs/node/pull/51044
Refs: https://github.com/nodejs/performance/issues/136
Reviewed-By: Vinícius Lourenço Claro Cardoso <contact@viniciusl.com.br>
Reviewed-By: Yagiz Nizipli <yagiz.nizipli@sentry.io>
2024-02-27 13:27:19 +01:00

44 lines
1.7 KiB
JavaScript

'use strict';
// This tests crypto.hash() works.
const common = require('../common');
if (!common.hasCrypto)
common.skip('missing crypto');
const assert = require('assert');
const crypto = require('crypto');
const fixtures = require('../common/fixtures');
const fs = require('fs');
// Test errors for invalid arguments.
[undefined, null, true, 1, () => {}, {}].forEach((invalid) => {
assert.throws(() => { crypto.hash(invalid, 'test'); }, { code: 'ERR_INVALID_ARG_TYPE' });
});
[undefined, null, true, 1, () => {}, {}].forEach((invalid) => {
assert.throws(() => { crypto.hash('sha1', invalid); }, { code: 'ERR_INVALID_ARG_TYPE' });
});
[null, true, 1, () => {}, {}].forEach((invalid) => {
assert.throws(() => { crypto.hash('sha1', 'test', invalid); }, { code: 'ERR_INVALID_ARG_TYPE' });
});
assert.throws(() => { crypto.hash('sha1', 'test', 'not an encoding'); }, { code: 'ERR_INVALID_ARG_VALUE' });
// Test that the output of crypto.hash() is the same as crypto.createHash().
const methods = crypto.getHashes();
const input = fs.readFileSync(fixtures.path('utf8_test_text.txt'));
for (const method of methods) {
for (const outputEncoding of ['buffer', 'hex', 'base64', undefined]) {
const oldDigest = crypto.createHash(method).update(input).digest(outputEncoding || 'hex');
const digestFromBuffer = crypto.hash(method, input, outputEncoding);
assert.deepStrictEqual(digestFromBuffer, oldDigest,
`different result from ${method} with encoding ${outputEncoding}`);
const digestFromString = crypto.hash(method, input.toString(), outputEncoding);
assert.deepStrictEqual(digestFromString, oldDigest,
`different result from ${method} with encoding ${outputEncoding}`);
}
}