-
Notifications
You must be signed in to change notification settings - Fork 24
/
randombytes.js
40 lines (31 loc) · 1.04 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
var assert = require('nanoassert')
var randombytes = (function () {
var QUOTA = 65536 // limit for QuotaExceededException
var crypto = global.crypto || global.msCrypto
function browserBytes (out, n) {
for (let i = 0; i < n; i += QUOTA) {
crypto.getRandomValues(new Uint8Array(out.buffer, i + out.byteOffset, Math.min(n - i, QUOTA)))
}
}
function nodeBytes (out, n) {
new Uint8Array(out.buffer, out.byteOffset, n).set(crypto.randomBytes(n))
}
function noImpl () {
throw new Error('No secure random number generator available')
}
if (crypto && crypto.getRandomValues) return browserBytes
if (require != null) {
// Node.js. Bust Browserify
crypto = require('cry' + 'pto')
if (crypto && crypto.randomBytes) return nodeBytes
}
return noImpl
})()
// Make non enumerable as this is an internal function
Object.defineProperty(module.exports, 'randombytes', {
value: randombytes
})
module.exports.randombytes_buf = function (out) {
assert(out, 'out must be given')
randombytes(out, out.byteLength)
}