-
Notifications
You must be signed in to change notification settings - Fork 1
/
random.js
221 lines (196 loc) · 6.59 KB
/
random.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
// We use cryptographically strong PRNGs (crypto.getRandomBytes() on the server,
// window.crypto.getRandomValues() in the browser) when available. If these
// PRNGs fail, we fall back to the Alea PRNG, which is not cryptographically
// strong, and we seed it with various sources such as the date, Math.random,
// and window size on the client. When using crypto.getRandomValues(), our
// primitive is hexString(), from which we construct fraction(). When using
// window.crypto.getRandomValues() or alea, the primitive is fraction and we use
// that to construct hex string.
if (typeof window === "undefined" && process)
// if (Meteor.isServer)
var nodeCrypto = require('crypto');
// see http://baagoe.org/en/wiki/Better_random_numbers_for_javascript
// for a full discussion and Alea implementation.
var Alea = function () {
function Mash() {
var n = 0xefc8249d;
var mash = function(data) {
data = data.toString();
for (var i = 0; i < data.length; i++) {
n += data.charCodeAt(i);
var h = 0.02519603282416938 * n;
n = h >>> 0;
h -= n;
h *= n;
n = h >>> 0;
h -= n;
n += h * 0x100000000; // 2^32
}
return (n >>> 0) * 2.3283064365386963e-10; // 2^-32
};
mash.version = 'Mash 0.9';
return mash;
}
return (function (args) {
var s0 = 0;
var s1 = 0;
var s2 = 0;
var c = 1;
if (args.length == 0) {
args = [+new Date];
}
var mash = Mash();
s0 = mash(' ');
s1 = mash(' ');
s2 = mash(' ');
for (var i = 0; i < args.length; i++) {
s0 -= mash(args[i]);
if (s0 < 0) {
s0 += 1;
}
s1 -= mash(args[i]);
if (s1 < 0) {
s1 += 1;
}
s2 -= mash(args[i]);
if (s2 < 0) {
s2 += 1;
}
}
mash = null;
var random = function() {
var t = 2091639 * s0 + c * 2.3283064365386963e-10; // 2^-32
s0 = s1;
s1 = s2;
return s2 = t - (c = t | 0);
};
random.uint32 = function() {
return random() * 0x100000000; // 2^32
};
random.fract53 = function() {
return random() +
(random() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53
};
random.version = 'Alea 0.9';
random.args = args;
return random;
} (Array.prototype.slice.call(arguments)));
};
var UNMISTAKABLE_CHARS = "23456789ABCDEFGHJKLMNPQRSTWXYZabcdefghijkmnopqrstuvwxyz";
var BASE64_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"0123456789-_";
// If seeds are provided, then the alea PRNG will be used, since cryptographic
// PRNGs (Node crypto and window.crypto.getRandomValues) don't allow us to
// specify seeds. The caller is responsible for making sure to provide a seed
// for alea if a csprng is not available.
var RandomGenerator = function (seedArray) {
var self = this;
if (seedArray !== undefined)
self.alea = Alea.apply(null, seedArray);
};
RandomGenerator.prototype.fraction = function () {
var self = this;
if (self.alea) {
return self.alea();
} else if (nodeCrypto) {
var numerator = parseInt(self.hexString(8), 16);
return numerator * 2.3283064365386963e-10; // 2^-32
} else if (typeof window !== "undefined" && window.crypto &&
window.crypto.getRandomValues) {
var array = new Uint32Array(1);
window.crypto.getRandomValues(array);
return array[0] * 2.3283064365386963e-10; // 2^-32
} else {
throw new Error('No random generator available');
}
};
RandomGenerator.prototype.hexString = function (digits) {
var self = this;
if (nodeCrypto && ! self.alea) {
var numBytes = Math.ceil(digits / 2);
var bytes;
// Try to get cryptographically strong randomness. Fall back to
// non-cryptographically strong if not available.
try {
bytes = nodeCrypto.randomBytes(numBytes);
} catch (e) {
// XXX should re-throw any error except insufficient entropy
bytes = nodeCrypto.pseudoRandomBytes(numBytes);
}
var result = bytes.toString("hex");
// If the number of digits is odd, we'll have generated an extra 4 bits
// of randomness, so we need to trim the last digit.
return result.substring(0, digits);
} else {
var hexDigits = [];
for (var i = 0; i < digits; ++i) {
hexDigits.push(self.choice("0123456789abcdef"));
}
return hexDigits.join('');
}
};
RandomGenerator.prototype._randomString = function (charsCount,
alphabet) {
var self = this;
var digits = [];
for (var i = 0; i < charsCount; i++) {
digits[i] = self.choice(alphabet);
}
return digits.join("");
};
RandomGenerator.prototype.id = function (charsCount) {
var self = this;
// 17 characters is around 96 bits of entropy, which is the amount of
// state in the Alea PRNG.
if (charsCount === undefined)
charsCount = 17;
return self._randomString(charsCount, UNMISTAKABLE_CHARS);
};
RandomGenerator.prototype.secret = function (charsCount) {
var self = this;
// Default to 256 bits of entropy, or 43 characters at 6 bits per
// character.
if (charsCount === undefined)
charsCount = 43;
return self._randomString(charsCount, BASE64_CHARS);
};
RandomGenerator.prototype.choice = function (arrayOrString) {
var index = Math.floor(this.fraction() * arrayOrString.length);
if (typeof arrayOrString === "string")
return arrayOrString.substr(index, 1);
else
return arrayOrString[index];
};
// instantiate RNG. Heuristically collect entropy from various sources when a
// cryptographic PRNG isn't available.
// client sources
var height = (typeof window !== 'undefined' && window.innerHeight) ||
(typeof document !== 'undefined'
&& document.documentElement
&& document.documentElement.clientHeight) ||
(typeof document !== 'undefined'
&& document.body
&& document.body.clientHeight) ||
1;
var width = (typeof window !== 'undefined' && window.innerWidth) ||
(typeof document !== 'undefined'
&& document.documentElement
&& document.documentElement.clientWidth) ||
(typeof document !== 'undefined'
&& document.body
&& document.body.clientWidth) ||
1;
var agent = (typeof navigator !== 'undefined' && navigator.userAgent) || "";
if (nodeCrypto ||
(typeof window !== "undefined" &&
window.crypto && window.crypto.getRandomValues))
Random = new RandomGenerator();
else
Random = new RandomGenerator([new Date(), height, width, agent, Math.random()]);
Random.createWithSeeds = function () {
if (arguments.length === 0) {
throw new Error('No seeds were provided');
}
return new RandomGenerator(arguments);
};
module.exports = Random;