Skip to content

Commit

Permalink
lib,build: use Web Crypto API in browser
Browse files Browse the repository at this point in the history
PR-URL: #360
Reviewed-By: Alexey Orlenko <eaglexrlnk@gmail.com>
Reviewed-By: Denys Otrishko <shishugi@gmail.com>
  • Loading branch information
belochub committed Aug 8, 2018
1 parent 209a363 commit d77434b
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 3 deletions.
30 changes: 30 additions & 0 deletions lib/common-crypto-fallback.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
'use strict';

/* eslint-env browser */

// Browser adapter for required functions from Node.js crypto module.
const crypto = {};

crypto.randomBytes = (count) => {
const buf = Buffer.alloc(count);
crypto.randomFillSync(buf);
return buf;
};

if (window.crypto && window.crypto.getRandomValues) {
crypto.randomFillSync = (buf) => {
window.crypto.getRandomValues(buf);
};
} else {
console.warn(
'Web Crypto API is not supported in your browser!',
'Using Math.random() instead.'
);
crypto.randomFillSync = (buf) => {
for (let i = 0; i < buf.length; i++) {
buf[i] = Math.floor(0x100 * Math.random());
}
};
}

module.exports = crypto;
8 changes: 7 additions & 1 deletion lib/common.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
'use strict';

const crypto = require('crypto');
let crypto;

if (typeof window !== 'undefined') {
crypto = require('./common-crypto-fallback');
} else {
crypto = require('crypto');
}

// Forward an event from one EventEmitter to another.
// from - EventEmitter to listen for event
Expand Down
3 changes: 1 addition & 2 deletions webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ module.exports = {
node: {
net: false,
tls: false,
// TODO: support WebCrypto API in lib/common.js and uncomment this
// crypto: 'empty',
crypto: 'empty',
},
};

0 comments on commit d77434b

Please sign in to comment.