-
Notifications
You must be signed in to change notification settings - Fork 0
/
randombytes.js
35 lines (30 loc) · 1.01 KB
/
randombytes.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
const getRandomValues = byteArray => {
for (let i = 0; i < byteArray.length; i++) {
byteArray[i] = Math.floor(256 * Math.random());
}
};
const randomBytes = (size, cb) => {
// phantomjs needs to throw
if (size > 65536) throw new Error("requested too many random bytes");
// in case browserify isn't using the Uint8Array version
var rawBytes = new global.Uint8Array(size);
// This will not work in older browsers.
// See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
if (size > 0) {
// getRandomValues fails on IE if size == 0
getRandomValues(rawBytes);
}
// XXX: phantomjs doesn't like a buffer being passed here
var bytes = Buffer.from(rawBytes.buffer);
if (cb) {
cb(bytes);
}
return bytes;
};
// these 2 lines are simply to make brorand work (used by eth-lightwallet)
global.self = global;
global.self.crypto = { getRandomValues };
const crypto = require("crypto");
window.crypto = crypto;
global.self.crypto = crypto;
module.exports = randomBytes;