A cryptographically secure generator for random numbers in a range.
npm install pure-random-number> A module for generating cryptographically secure pseudo-random numbers.
Zero dependencies ~56LOC, pure es6/esm, runs on browser + node without transpilation.
This module is based on code originally written by Scott Arciszewski, (WTFPL / CC0 / ZAP)
Basic:
``js
import { randomNumber } from 'pure-random-number'
const n = await randomNumber(1, 20) // defaults to crypto:subtle getRandomValues()
console.log('Cryptographically Secure Random Number', n)
`
Bring your own generator:
`js
let prevHash = await sha256('Hello World')
const prng = async (nBytes) => {
if (nBytes > 32) throw new Error('Entropy unsupported')
prevHash = await sha256(prevHash)
return prevHash
}
const n = await randomNumber(1, 20, prng)
console.log('Deterministic Random Number', n)
`
see JSdoc annotations for accurate descriptions.
Returns a stable random positive integer within the specified range.
Note that the range is __inclusive__, and both numbers __must be positive integer values__.
It is not possible to securely generate a random value for floating point numbers, so if you are working with fractional numbers (eg. 1.24), you will have to decide on a fixed 'precision' and turn them into integer values (eg. 124).
Returns amount of bytes required for a given range
Returns a stable random positive integer extracted from seed within the specified range.
and MAX_SAFE_INTEGER, and the correct bitwise operator is used (>>> rather than >>`).Apache 2.0 - Decent Labs