sodium-javascript/randombytes.js

41 lines
991 B
JavaScript
Raw Normal View History

2017-06-19 20:32:33 +00:00
var assert = require('nanoassert')
2020-06-24 11:37:07 +00:00
2017-06-19 20:32:33 +00:00
var randombytes = (function () {
var QUOTA = 65536 // limit for QuotaExceededException
2020-06-24 11:37:07 +00:00
var crypto = global.crypto || global.msCrypto
2017-06-19 20:32:33 +00:00
function browserBytes (out, n) {
2020-06-24 12:08:55 +00:00
for (let i = 0; i < n; i += QUOTA) {
2017-06-19 20:32:33 +00:00
crypto.getRandomValues(out.subarray(i, i + Math.min(n - i, QUOTA)))
}
}
function nodeBytes (out, n) {
out.set(crypto.randomBytes(n))
}
function noImpl () {
throw new Error('No secure random number generator available')
}
2020-06-24 11:37:07 +00:00
if (crypto && crypto.getRandomValues) return browserBytes
if (require != null) {
// Node.js. Bust Browserify
crypto = require('cry' + 'pto')
2020-06-24 11:37:16 +00:00
if (crypto && crypto.randomBytes) return nodeBytes
2017-06-19 20:32:33 +00:00
}
return noImpl
})()
2020-06-24 11:37:07 +00:00
// Make non enumerable as this is an internal function
2017-06-19 20:32:33 +00:00
Object.defineProperty(module.exports, 'randombytes', {
value: randombytes
})
module.exports.randombytes_buf = function (out) {
assert(out, 'out must be given')
randombytes(out, out.length)
}