2017-06-19 20:32:33 +00:00
|
|
|
var assert = require('nanoassert')
|
2020-06-24 11:37:07 +00:00
|
|
|
|
2022-11-21 17:17:47 +00:00
|
|
|
const {
|
|
|
|
crypto_stream_chacha20_ietf,
|
|
|
|
crypto_stream_chacha20_ietf_KEYBYTES,
|
|
|
|
crypto_stream_chacha20_ietf_NONCEBYTES
|
|
|
|
} = require('./crypto_stream_chacha20')
|
|
|
|
|
|
|
|
const randombytes_SEEDBYTES = 32
|
|
|
|
|
2017-06-19 20:32:33 +00:00
|
|
|
var randombytes = (function () {
|
|
|
|
var QUOTA = 65536 // limit for QuotaExceededException
|
2021-11-02 15:36:15 +00:00
|
|
|
var crypto = globalThis.crypto || globalThis.msCrypto
|
2017-06-19 20:32:33 +00:00
|
|
|
|
2017-11-03 07:17:38 +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
|
|
|
|
})
|
|
|
|
|
2022-11-21 17:17:47 +00:00
|
|
|
function randombytes_buf (out) {
|
2017-06-19 20:32:33 +00:00
|
|
|
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
|
|
|
}
|
2022-11-21 17:17:47 +00:00
|
|
|
|
|
|
|
function randombytes_buf_deterministic (buf, seed) {
|
|
|
|
const nonce = Buffer.alloc(crypto_stream_chacha20_ietf_NONCEBYTES)
|
|
|
|
nonce.write('LibsodiumDRG')
|
|
|
|
|
|
|
|
assert(randombytes_SEEDBYTES === crypto_stream_chacha20_ietf_KEYBYTES)
|
|
|
|
crypto_stream_chacha20_ietf(buf, nonce, seed)
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
randombytes_buf,
|
|
|
|
randombytes_buf_deterministic,
|
|
|
|
randombytes_SEEDBYTES
|
|
|
|
}
|