UNPKG

1.51 kBJavaScriptView Raw
1var r;
2
3module.exports = function rand(len) {
4 if (!r)
5 r = new Rand(null);
6
7 return r.generate(len);
8};
9
10function Rand(rand) {
11 this.rand = rand;
12}
13module.exports.Rand = Rand;
14
15Rand.prototype.generate = function generate(len) {
16 return this._rand(len);
17};
18
19// Emulate crypto API using randy
20Rand.prototype._rand = function _rand(n) {
21 if (this.rand.getBytes)
22 return this.rand.getBytes(n);
23
24 var res = new Uint8Array(n);
25 for (var i = 0; i < res.length; i++)
26 res[i] = this.rand.getByte();
27 return res;
28};
29
30if (typeof self === 'object') {
31 if (self.crypto && self.crypto.getRandomValues) {
32 // Modern browsers
33 Rand.prototype._rand = function _rand(n) {
34 var arr = new Uint8Array(n);
35 self.crypto.getRandomValues(arr);
36 return arr;
37 };
38 } else if (self.msCrypto && self.msCrypto.getRandomValues) {
39 // IE
40 Rand.prototype._rand = function _rand(n) {
41 var arr = new Uint8Array(n);
42 self.msCrypto.getRandomValues(arr);
43 return arr;
44 };
45
46 // Safari's WebWorkers do not have `crypto`
47 } else if (typeof window === 'object') {
48 // Old junk
49 Rand.prototype._rand = function() {
50 throw new Error('Not implemented yet');
51 };
52 }
53} else {
54 // Node.js or Web worker with no crypto support
55 try {
56 var crypto = require('crypto');
57 if (typeof crypto.randomBytes !== 'function')
58 throw new Error('Not supported');
59
60 Rand.prototype._rand = function _rand(n) {
61 return crypto.randomBytes(n);
62 };
63 } catch (e) {
64 }
65}