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:
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:
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.
- 3.2.0 (July 7, 2024) Removed obsolete validators, exported sync randomSeedNumber() & bytesNeeded()
- 3.0.0 (July 7, 2024): Converted to ESM, removed sync version
- 2.1.0 (June 12, 2020): Added sync version.
- 2.0.0 (May 3, 2020): Removed dependencies and ported to standardjs
- 1.0.2 (March 8, 2016): Security release! Patched handling of large numbers; input values are now checked for
MIN_SAFE_INTEGER
andMAX_SAFE_INTEGER
, and the correct bitwise operator is used (>>>
rather than>>
). - 1.0.1 (March 8, 2016): Unimportant file cleanup.
- 1.0.0 (March 8, 2016): Initial release.
Apache 2.0 - Decent Labs