sodium-javascript/randombytes.js

62 lines
1.5 KiB
JavaScript
Raw Normal View History

2017-06-19 20:32:33 +00:00
var assert = require('nanoassert')
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
var crypto = typeof global !== 'undefined' ? crypto = (global.crypto || global.msCrypto) : null
2017-06-19 20:32:33 +00:00
function browserBytes (out, n) {
2017-06-19 20:32:33 +00:00
for (var i = 0; i < n; i += QUOTA) {
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')
}
if (crypto && crypto.getRandomValues) {
return browserBytes
2017-06-19 20:32:33 +00:00
} else if (typeof require !== 'undefined') {
// Node.js.
2017-11-19 12:16:13 +00:00
crypto = require('crypto')
2017-06-19 20:32:33 +00:00
if (crypto && crypto.randomBytes) {
return nodeBytes
}
}
return noImpl
})()
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')
randombytes(out, out.length)
}
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
}