From e8a2c453903e988ba8e3e45b63bddc4c6e8b4235 Mon Sep 17 00:00:00 2001 From: Daniel Huigens Date: Thu, 1 Nov 2018 10:48:25 +0100 Subject: [PATCH] Only use Web Crypto for hashing beyond a treshold number of bytes Sending data to the Web Crypto API involves some latency. --- src/config/config.js | 5 +++++ src/crypto/hash/index.js | 6 ++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/config/config.js b/src/config/config.js index d11b217c..8fb39185 100644 --- a/src/config/config.js +++ b/src/config/config.js @@ -126,6 +126,11 @@ export default { * @property {Boolean} use_native Use native Node.js crypto/zlib and WebCrypto APIs when available */ use_native: true, + /** + * @memberof module:config + * @property {Integer} min_bytes_for_web_crypto The minimum amount of bytes for which to use native WebCrypto APIs when available + */ + min_bytes_for_web_crypto: 1000, /** * @memberof module:config * @property {Boolean} Use transferable objects between the Web Worker and main thread diff --git a/src/crypto/hash/index.js b/src/crypto/hash/index.js index 1d829611..bbb977b3 100644 --- a/src/crypto/hash/index.js +++ b/src/crypto/hash/index.js @@ -6,6 +6,7 @@ * @requires hash.js * @requires web-stream-tools * @requires crypto/hash/md5 + * @requires config * @requires util * @module crypto/hash */ @@ -18,6 +19,7 @@ import sha512 from 'hash.js/lib/hash/sha/512'; import { ripemd160 } from 'hash.js/lib/hash/ripemd'; import stream from 'web-stream-tools'; import md5 from './md5'; +import config from '../../config'; import util from '../../util'; const webCrypto = util.getWebCrypto(); @@ -35,7 +37,7 @@ function node_hash(type) { function hashjs_hash(hash, webCryptoHash) { return async function(data) { - if (!util.isStream(data) && webCrypto && webCryptoHash) { + if (!util.isStream(data) && webCrypto && webCryptoHash && data.length >= config.min_bytes_for_web_crypto) { return new Uint8Array(await webCrypto.digest(webCryptoHash, data)); } const hashInstance = hash(); @@ -52,7 +54,7 @@ function asmcrypto_hash(hash, webCryptoHash) { return stream.transform(data, value => { hashInstance.process(value); }, () => hashInstance.finish().result); - } else if (webCrypto && webCryptoHash) { + } else if (webCrypto && webCryptoHash && data.length >= config.min_bytes_for_web_crypto) { return new Uint8Array(await webCrypto.digest(webCryptoHash, data)); } else { return hash.bytes(data);