public final class SecureRandom
- Object
- SecureRandom
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
Methods
public static byte[] bytes(int length) | Returns a fresh length-byte array filled with secure random bytes. |
public static void fill(byte[] out) | Fills out with secure random bytes. |
public static int intBelow(int bound) | Returns a uniformly distributed random int in [0, bound). |
public static long longBelow(long bound) | Returns a uniformly distributed random long in [0, bound). |
Inherited methods
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.