Generating a Secure Random Number - Java Language Basics

Java examples for Language Basics:Random

Description

Generating a Secure Random Number

Demo Code

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

public class Main {
  public void myMethod() {
    try {/*  www  .j av  a  2 s . c  o  m*/
      // Create a secure random number generator
      SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");

      // Get 1024 random bits
      byte[] bytes = new byte[1024 / 8];
      sr.nextBytes(bytes);

      // Create two secure number generators with the same seed
      int seedByteCount = 10;
      byte[] seed = sr.generateSeed(seedByteCount);

      sr = SecureRandom.getInstance("SHA1PRNG");
      sr.setSeed(seed);
      SecureRandom sr2 = SecureRandom.getInstance("SHA1PRNG");
      sr2.setSeed(seed);
    } catch (NoSuchAlgorithmException e) {
    }
  }
}

Related Tutorials