Back to cheatsheets
Cryptography
Random Number Generation
Bias-free random values with rejection sampling and Fisher-Yates shuffle from real entropy.
What you'll learn
- Unbiased random integer
- Fisher-Yates shuffle
- Random range and dice
How to use these snippets
- Click the Copy button next to any snippet to copy it to your clipboard.
- Paste the code into your project, IDE, or terminal.
- Replace placeholder values (like
example.comoryour-secret) with your actual data. - Review the code comments for important security notes and caveats.
- Try the interactive related tool to see the concept in action.
Code Snippets
Copy-paste code snippets
3 ready-to-use snippets for random number generation. Click copy and paste into your project.
Unbiased random integer
function randomInt(max) {
const arr = new Uint32Array(1);
const limit = 0xFFFFFFFF - (0xFFFFFFFF % max);
do { crypto.getRandomValues(arr); }
while (arr[0] >= limit);
return arr[0] % max;
}
Fisher-Yates shuffle
function shuffle(arr) {
for (let i = arr.length - 1; i > 0; i--) {
const j = randomInt(i + 1);
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
Random range and dice
// Random in range [min, max] inclusive
function randomRange(min, max) {
return min + randomInt(max - min + 1);
}
// Dice roll (D4, D6, D8, D10, D12, D20, D100)
function rollDice(sides) {
return 1 + randomInt(sides);
}
// Crypto-secure random bytes
function randomBytes(n) {
const arr = new Uint8Array(n);
crypto.getRandomValues(arr);
return arr;
}
Tool
Related ShieldX tool
Try this concept hands-on with the interactive tool.
100% Free · No signup · No cost
Generate something unguessable right now
148 bits of entropy, a crack-time estimate you can trust, and a clipboard that clears itself after 30 seconds.
Part of the Toolly ecosystem · secure.toolly.site