ShieldX Toolly
Open a tool Donate
Home Home
Blog Blog
FAQ FAQ
Open a tool Donate
Back to cheatsheets
Cryptography

Random Number Generation

Bias-free random values with rejection sampling and Fisher-Yates shuffle from real entropy.

3 snippets Beginner random-number-generator
CSPRNGrejection samplingFisher-Yatesdice

What you'll learn

  • Unbiased random integer
  • Fisher-Yates shuffle
  • Random range and dice

How to use these snippets

  1. Click the Copy button next to any snippet to copy it to your clipboard.
  2. Paste the code into your project, IDE, or terminal.
  3. Replace placeholder values (like example.com or your-secret) with your actual data.
  4. Review the code comments for important security notes and caveats.
  5. 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

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.

Open the toolkit

Part of the Toolly ecosystem · secure.toolly.site