• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer

Mister PKI

SSL Certificates * SSL Tools * Certificate Decoder

  • Buy SSL Certificates
  • Blog
  • OpenSSL
  • Keytool
  • SSL Tools
  • Donate

Java SecureRandom

February 11, 2021 by Mister PKI Leave a Comment

Java SecureRandom lives in the java.security package, at java.security.SecureRandom. The number or value generated by this class is cryptographically strong and the generator is also known as a secure pseudo-random number generator (CSPRNG).

Java SecureRandom examples

The examples specify NativePRNG for demonstration purposes of how to specify your choice of algorithm rather than using the default. The code in the following examples is in our GitHub Repository.

Generate a secure random int:

public static int generateRandomInt() throws NoSuchAlgorithmException {
    final SecureRandom secureRandom = SecureRandom.getInstance("NativePRNG");
  return secureRandom.nextInt();
}

For each example, calling nextX will get you the next random number and will not be the same.

You can also provide an upper bound to your generator. If you set the upper bound at 100, the random number will not go over 100.

public static int generateRandomIntWithUpperBound(final int bound) throws NoSuchAlgorithmException {
    final SecureRandom secureRandom = SecureRandom.getInstance("NativePRNG");
    return secureRandom.nextInt(bound);
  }

An additional method is to generate a stream of values. For an a stream of ints:

public static IntStream generateRandomStreamOfInts(final int size, final int lowerBound, final int upperBound) throws NoSuchAlgorithmException {
    final SecureRandom secureRandom = SecureRandom.getInstance("NativePRNG");
    return secureRandom.ints(size, lowerBound, upperBound);
  }

To print this stream by using a forEach:

generateRandomStreamOfInts(3, 1, 10)
        .forEach(value -> System.out.println("Value: " + value));

Generate a secure random long:

public static long generateRandomLong() throws NoSuchAlgorithmException {
    final SecureRandom secureRandom = SecureRandom.getInstance("NativePRNG");
    return secureRandom.nextLong();
  }

Generate a secure random float:

public static float generateRandomFloat() throws NoSuchAlgorithmException {
    final SecureRandom secureRandom = SecureRandom.getInstance("NativePRNG");
    return secureRandom.nextFloat();
  }

Generate a secure random double:

public static double generateRandomDouble() throws NoSuchAlgorithmException {
    final SecureRandom secureRandom = SecureRandom.getInstance("NativePRNG");
    return secureRandom.nextDouble();
  }

Generate a secure random gaussian:

public static double generateRandomGaussian() throws NoSuchAlgorithmException {
    final SecureRandom secureRandom = SecureRandom.getInstance("NativePRNG");
    return secureRandom.nextGaussian();
  }

Generate a secure random boolean:

public static boolean generateRandomBoolean() throws NoSuchAlgorithmException {
    final SecureRandom secureRandom = SecureRandom.getInstance("NativePRNG");
    return secureRandom.nextBoolean();
  }

An interesting example to see the randomness by this feature is to loop through 100 generations and view the output.

int trueCount = 0;
int falseCount = 0;
for (int i = 0; i < 100; i++) {
  if (SecureRandomNumberGenerator.generateRandomBoolean()) {
    trueCount++;
  } else {
    falseCount++;
  }
}
System.out.println("True Count: " + trueCount);
System.out.println("False Count: " + falseCount);

Generate secure random bytes:

public static byte[] generateRandomBytes() throws NoSuchAlgorithmException {
    final SecureRandom secureRandom = SecureRandom.getInstance("NativePRNG");
    byte[] bytes = new byte[16];
    secureRandom.nextBytes(bytes);
    return bytes;
  }

Java SecureRandom performance

Performance of SecureRandom in Java is dependent on the algorithm you specify. It’s best to try out each algorithm on your OS and compare the performance in your environment.

Random vs SecureRandom numbers in Java

The java.util.Random class also provides random numbers, but this class is not considered cryptographically strong or secure. The values generated from java.util.Random can more easily be predicted.

SecureRandom Number Generation Algorithms

  • NativePRNG – May be blocking, obtaining randomness from the OS.
  • NativePRNGBlocking – Blocking, obtaining randomness from the OS.
  • NativePRNGNonBlocking – Non-blocking, obtaining randomness from the OS.
  • PKCS11 – Obtains randomness from a configured PKCS11 library.
  • SHA1PRNG – Provided by SUN, default.
  • Windows-PRNG – Obtains randomness from Windows.

Review the SecureRandom code in GitHub.

Read more of our content.

Uncategorized

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

Popular Posts

PKCS12

openssl s_client

Keytool

Keytool list

ECDSA vs RSA

OpenSSL

PKCS7

Certificate Decoder

Training Courses

Top online courses in IT & Software

Cyber Security Training

Udemy - The Complete Internet Security Privacy Course icon

Buy SSL Certificates

The SSL Store

Comodo Store

Sectigo Store

RapidSSL

Recent Posts

  • pfx password
  • pkcs12
  • Sendmail vs Postfix – Mail Transfer Agent Comparison
  • Python mock datetime now
  • Python get SSL Certificate

Footer

  • Twitter
  • YouTube

Pages

  • About Mister PKI
  • Blog
  • Compare and Buy Affordable PKI Certificates
  • Contact Us
  • Full Disclosure
  • Privacy Policy
  • SSL Tools – Certificate Decoder and Certificate Checker

Copyright © 2022