sodium-javascript/randombytes.js

41 lines
1.0 KiB
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) {
2020-06-24 13:01:10 +00:00
crypto.getRandomValues(new Uint8Array(out.buffer, i + out.byteOffset, Math.min(n - i, QUOTA)))
2017-06-19 20:32:33 +00:00
}
}
function nodeBytes (out, n) {
2020-06-24 13:01:10 +00:00
new Uint8Array(out.buffer, out.byteOffset, n).set(crypto.randomBytes(n))
2017-06-19 20:32:33 +00:00
}
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')
2020-06-24 12:55:46 +00:00
randombytes(out, out.byteLength)
2017-06-19 20:32:33 +00:00
}