Java – How to generate a random 12 bytes?

In Java, we can use SecureRandom.nextBytes(byte[] bytes) to generate a user-specified number of random bytes. This SecureRandom is a cryptographically secure random number generator (RNG).

1. Random 12 bytes (96 bits)

1.1 Generates a random 12 bytes (96 bits) nonce.

HelloCryptoApp.java

package com.mkyong.crypto;

import java.security.SecureRandom;

public class HelloCryptoApp {

    public static void main(String[] args) {

        byte[] nonce = new byte[12];
        new SecureRandom().nextBytes(nonce);

        System.out.println(convertBytesToHex(nonce));

    }

    // util to print bytes in hex
    private static String convertBytesToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte temp : bytes) {
            result.append(String.format("%02x", temp));
        }
        return result.toString();
    }

}

Output

Terminal

0747a9ad467d4dc29ce70344

1.2 Generates a random 20 bytes (160 bits)


  byte[] nonce = new byte[20];
  new SecureRandom().nextBytes(nonce);

  System.out.println(convertBytesToHex(nonce));

Output

Terminal

e2ac8893b23ef174461e4ec37598080ec910b87b

2. Random 32 bytes (256 bits) + DRBG algorithm

2.1 Generates a random 32 bytes (256 bits) with the DRBG algorithm defined in NIST SP 800-90Ar1. By default, SecureRandom uses the SHA1PRNG algorithm to generate a random number.

HelloCryptoApp2.java

package com.mkyong.java11;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class HelloCryptoApp2 {

    public static void main(String[] args) throws NoSuchAlgorithmException {

        byte[] nonce = new byte[32];
        SecureRandom rand = SecureRandom.getInstance("DRBG");
        rand.nextBytes(nonce);

        System.out.println(convertBytesToHex(nonce));

    }

    private static String convertBytesToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte temp : bytes) {
            result.append(String.format("%02x", temp));
        }
        return result.toString();
    }

}

Output

Terminal

7d5bca7a4cfab6abec28da5cc899c32a0c36f17128f242a3df20301b3812b881

Further Reading
For all supported random algorithm, refer to this SecureRandom Number Generation Algorithms

References

author image

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities. Read all published posts by

Comments

avatar