Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80575 views
1
var r;
2
3
module.exports = function rand(len) {
4
if (!r)
5
r = new Rand(null);
6
7
return r.generate(len);
8
};
9
10
function Rand(rand) {
11
this.rand = rand;
12
}
13
module.exports.Rand = Rand;
14
15
Rand.prototype.generate = function generate(len) {
16
return this._rand(len);
17
};
18
19
if (typeof window === 'object') {
20
if (window.crypto && window.crypto.getRandomValues) {
21
// Modern browsers
22
Rand.prototype._rand = function _rand(n) {
23
var arr = new Uint8Array(n);
24
window.crypto.getRandomValues(arr);
25
return arr;
26
};
27
} else if (window.msCrypto && window.msCrypto.getRandomValues) {
28
// IE
29
Rand.prototype._rand = function _rand(n) {
30
var arr = new Uint8Array(n);
31
window.msCrypto.getRandomValues(arr);
32
return arr;
33
};
34
} else {
35
// Old junk
36
Rand.prototype._rand = function() {
37
throw new Error('Not implemented yet');
38
};
39
}
40
} else {
41
// Node.js or Web worker
42
try {
43
var crypto = require('cry' + 'pto');
44
45
Rand.prototype._rand = function _rand(n) {
46
return crypto.randomBytes(n);
47
};
48
} catch (e) {
49
// Emulate crypto API using randy
50
Rand.prototype._rand = function _rand(n) {
51
var res = new Uint8Array(n);
52
for (var i = 0; i < res.length; i++)
53
res[i] = this.rand.getByte();
54
return res;
55
};
56
}
57
}
58
59