Comment en Générer Random Nombres
Générer cryptographically secure random numbers, integers, and bytes.
问题
You besoin random nombres pour sécurité purposes, testing, ou simulation, et doit ensure proper randomness.
Prérequis
- Understanding of PRNG vs CSPRNG
- Knowledge of random number ranges
Étapes
-
1. Choose the right generator
For security purposes (tokens, keys, passwords), use a cryptographically secure PRNG (CSPRNG): crypto.getRandomValues in browsers, crypto.randomBytes in Node.js. For non-security uses (testing, simulation), Math.random is faster but not secure. Never use Math.random for security.
entréepurpose: security token输出use CSPRNG -
2. Generate within the desired range
For a random integer in [min, max], generate random bytes and map to the range. Avoid modulo bias: use rejection sampling or generate enough bits to cover the range uniformly. For random floats in [0, 1), divide a large random integer by its maximum value.
entréerange: [1, 100]输出42 (uniform) -
3. Generate other random types
For random bytes (e.g., for a key), generate the required number of bytes directly. For random hex strings, convert the bytes to hex. For UUIDs, use the dedicated UUID generator. For random selections from an array, use a random index.
entrée32 random bytes输出a1b2c3... (64 hex chars)
Résultat attendu
Random valeurs généré avec le appropriate niveau de sécurité et uniformity.
Erreurs courantes
- Modulo bias when using % to range
- Using randomNumber % range produces biased results when the range doesn't evenly divide the generator's range. Use rejection sampling or crypto.randomInt for unbiased results.
- Using Math.random for security
- Math.random is predictable and not cryptographically secure. Always use crypto.getRandomValues or crypto.randomBytes for security-sensitive randomness.
Dépannage指引
- If random values seem predictable, verify you are using a CSPRNG.
- For large numbers of random values, check the distribution for uniformity.
Limites de sécurité
- All random generation is local. No random values are transmitted.
- CSPRNG output is unpredictable and suitable for security tokens, keys, and nonces.