コンテンツへスキップ
uencoder

乱数を生成する方法

暗号学的に安全な乱数、整数、バイト列を生成します。

问题

セキュリティ、テスト、シミュレーションの目的で乱数が必要であり、適切なランダム性を保証しなければなりません。

前提条件

  • PRNG と CSPRNG の違いの理解
  • 乱数の範囲に関する知識

ステップ

  1. 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.

    入力
    purpose: security token
    输出
    use CSPRNG
  2. 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.

    入力
    range: [1, 100]
    输出
    42 (uniform)
  3. 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.

    入力
    32 random bytes
    输出
    a1b2c3... (64 hex chars)

期待される結果

目的に応じた適切なセキュリティ強度と一様性で生成された乱数。

よくあるエラー

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.

トラブルシューティング指引

  • If random values seem predictable, verify you are using a CSPRNG.
  • For large numbers of random values, check the distribution for uniformity.

セキュリティ上の制限

  • All random generation is local. No random values are transmitted.
  • CSPRNG output is unpredictable and suitable for security tokens, keys, and nonces.

関連ツール

参考链接