sodium-javascript/randombytes.js
Arne Goedeke f93d546ee0 randombytes: Replace run-time require detection
Using require() as an expression leads to compile errors in webpack.
This issue can be solved by guarding the use of require by the 'correct'
run-time check using `typeof require`.
2023-03-02 09:48:16 +01:00

41 lines
1.1 KiB
JavaScript

var assert = require('nanoassert')
var randombytes = (function () {
var QUOTA = 65536 // limit for QuotaExceededException
var crypto = globalThis.crypto || globalThis.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 (typeof require === 'function') {
// 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)
}