Pavle Jonoski
By Pavle Jonoski

Cryptographically Secure Random in Java

Cryptographically Secure Random in Java

Generate cryptographically secure random number in Java

In many cases you might need to generate a cryptographically secure random number. The difference between a random number

generated using the standard Random generator or via ThreadLocalRandom, is that the algorithm used to generate the

pseudo-random number (PRNG) is usually cryptographically strong i.e. the probability of predicting the random number is very

small. The typical usage of such generated numbers and values is when you need to generate a secret key/password or other random bytes which are hard to guess and most often used in authentication/authorization flows, or when generating random secret keys for encryption.

To generate a cryptographically secure random numbers or sequences in Java, you should use SecureRandom.

Here is a simple example of generating a random integer:

1
2
3
4
5
6
7
SecureRandom random = new SecureRandom();

var i = random.nextInt();

System.out.println("This is my random number: " + i);

SecureRandom extends the Random class and implements all methods already exposed in Random, so it can be used as a drop-in replacement for it.

Here are some more examples.

Generate a random sequence of bytes:

1
2
3
4
5
6
7
8
9
10
11
SecureRandom random = new SecureRandom();



byte[] buffer = new byte[128];

random.nextBytes(buffer);

// we have now generated a 128 bytes with random values.

Generate a random base64 string:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.security.SecureRandom;

import java.util.Base64;



public class CryptoSafeRandom {



    public static void main(String[] args) {

        SecureRandom random = new SecureRandom();

        var buffer = new byte[12];

        random.nextBytes(buffer);

        String randomString = Base64.getEncoder().encodeToString(buffer);

        System.out.println("This is my cryptographically secure random string: " + randomString);

    }

}

Output:

1
2
3
This is my cryptographically secure random string: D++46PI36dOUmhHI