-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
41 lines (38 loc) · 1.2 KB
/
index.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
/* eslint-disable no-var, operator-linebreak */
var window = require('global/window');
var nodeCrypto = require('crypto');
/**
* @template {ArrayBufferView | null} T
* @param {T} buf
* @returns {T}
*/
function getRandomValues(buf) {
if (window.crypto && window.crypto.getRandomValues) {
return window.crypto.getRandomValues(buf);
}
if (typeof window.msCrypto === 'object' && typeof window.msCrypto.getRandomValues === 'function') {
return window.msCrypto.getRandomValues(buf);
}
if (nodeCrypto.randomBytes) {
if (!(buf instanceof Uint8Array)) {
throw new TypeError('expected Uint8Array');
}
if (buf.length > 65536) {
var e = new Error();
// @ts-expect-error
e.code = 22;
e.message = 'Failed to execute \'getRandomValues\' on \'Crypto\': The ' +
'ArrayBufferView\'s byte length (' + buf.length + ') exceeds the ' +
'number of bytes of entropy available via this API (65536).';
e.name = 'QuotaExceededError';
throw e;
}
var bytes = nodeCrypto.randomBytes(buf.length);
buf.set(bytes);
return buf;
}
else {
throw new Error('No secure random number generator available.');
}
}
module.exports = getRandomValues;