Only use Web Crypto for hashing beyond a treshold number of bytes

Sending data to the Web Crypto API involves some latency.
This commit is contained in:
Daniel Huigens 2018-11-01 10:48:25 +01:00
parent 7253df1632
commit e8a2c45390
2 changed files with 9 additions and 2 deletions

View File

@ -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

View File

@ -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);