Class SecureRandom

java.lang.Object
com.codename1.security.SecureRandom

public final class SecureRandom extends Object

Cryptographically secure random number generator. Delegates to the platform's native CSPRNG (/dev/urandom on Unix-style systems, the Windows BCryptGenRandom on Windows, SecRandomCopyBytes on iOS, the hardware RNG on devices that expose one).

Use this class -- not java.util.Random or Math.random() -- whenever the output is going to be used as a key, nonce, salt, session token, password reset code or any other security-sensitive value.

Example
byte[] iv = SecureRandom.bytes(12); // AES-GCM nonce
int code  = SecureRandom.intBelow(1_000_000); // 6-digit code
  • Method Summary

    Modifier and Type
    Method
    Description
    static byte[]
    bytes(int length)
    Returns a fresh length-byte array filled with secure random bytes.
    static void
    fill(byte[] out)
    Fills out with secure random bytes.
    static int
    intBelow(int bound)
    Returns a uniformly distributed random int in [0, bound).
    static long
    longBelow(long bound)
    Returns a uniformly distributed random long in [0, bound).

    Methods inherited from class Object

    clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Method Details

    • bytes

      public static byte[] bytes(int length)
      Returns a fresh length-byte array filled with secure random bytes.
    • fill

      public static void fill(byte[] out)
      Fills out with secure random bytes.
    • intBelow

      public static int intBelow(int bound)
      Returns a uniformly distributed random int in [0, bound). bound must be positive.
    • longBelow

      public static long longBelow(long bound)
      Returns a uniformly distributed random long in [0, bound). bound must be positive.