UNPKG

1.06 kBJavaScriptView Raw
1var assert = require('nanoassert')
2
3var randombytes = (function () {
4 var QUOTA = 65536 // limit for QuotaExceededException
5 var crypto = global.crypto || global.msCrypto
6
7 function browserBytes (out, n) {
8 for (let i = 0; i < n; i += QUOTA) {
9 crypto.getRandomValues(new Uint8Array(out.buffer, i + out.byteOffset, Math.min(n - i, QUOTA)))
10 }
11 }
12
13 function nodeBytes (out, n) {
14 new Uint8Array(out.buffer, out.byteOffset, n).set(crypto.randomBytes(n))
15 }
16
17 function noImpl () {
18 throw new Error('No secure random number generator available')
19 }
20
21 if (crypto && crypto.getRandomValues) return browserBytes
22
23 if (require != null) {
24 // Node.js. Bust Browserify
25 crypto = require('cry' + 'pto')
26 if (crypto && crypto.randomBytes) return nodeBytes
27 }
28
29 return noImpl
30})()
31
32// Make non enumerable as this is an internal function
33Object.defineProperty(module.exports, 'randombytes', {
34 value: randombytes
35})
36
37module.exports.randombytes_buf = function (out) {
38 assert(out, 'out must be given')
39 randombytes(out, out.byteLength)
40}