forked from dchest/tweetnacl-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
randomBytes.js
52 lines (48 loc) · 1.62 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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
export let randombytes = function(/* x, n */) { throw new Error('no PRNG'); };
export function setPRNG(fn) {
randombytes = fn;
}
export function randomBytes(n) {
const b = new Uint8Array(n);
randombytes(b, n);
return b;
}
function cleanup(arr) {
for (let i = 0; i < arr.length; i++) arr[i] = 0;
}
(function() {
// Initialize PRNG if environment provides CSPRNG.
// If not, methods calling randombytes will throw.
let crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null;
if (crypto && crypto.getRandomValues) {
// Browsers.
var QUOTA = 65536;
setPRNG(function(x, n) {
let i, v = new Uint8Array(n);
for (i = 0; i < n; i += QUOTA) {
crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));
}
for (i = 0; i < n; i++) x[i] = v[i];
cleanup(v);
});
} else if (typeof require !== 'undefined') {
// Node.js commonJS.
crypto = require('crypto');
if (crypto && crypto.randomBytes) {
setPRNG(function(x, n) {
let i, v = crypto.randomBytes(n);
for (i = 0; i < n; i++) x[i] = v[i];
cleanup(v);
});
}
} else if (typeof import.meta !== 'undefined' && typeof process !== 'undefined'){
// Node.js ESM
import('crypto').then((crypto) => {
setPRNG(function(x, n) {
const v = crypto.getRandomValues(new Uint8Array(n));
for (let i = 0; i < n; i++) x[i] = v[i];
cleanup(v);
});
})
}
})();