/* * Sequence.java * * R. Perry, July 1998 */ package sequence; import java.security.*; import java.io.*; /** * Generation and comparisons of a sequence of pseudo-random long values. * * @author Rick Perry * @version Mon Jul 20 12:44:24 EDT 1998 */ public class Sequence { /** * The SecureRandom seed. */ private byte[] seed; /** * The SecureRandom instance. */ private SecureRandom rand; /** * Current sequence number. */ private long current; /** * Constructs a sequence using the specified seed * to initialize the SecureRandom instance. * * @param seed array of 20 bytes. * @exception IllegalArgumentException * if the seed argument is null or its length is not 20. */ public Sequence( byte[] seed) { if( seed == null) throw new IllegalArgumentException( "bad seed = null"); if( seed.length != 20) throw new IllegalArgumentException( "bad seed length (" + seed.length + ") != 20"); this.seed = seed; rand = new SecureRandom( seed); current = rand.nextLong(); } /** * Constructs a sequence using SecureRandom.getSeed() * to initialize the SecureRandom instance. */ public Sequence() { this( SecureRandom.getSeed(20)); // this call takes some time } /** * Returns the seed used to initialize the sequence. * * @return the 20-byte seed array. */ public byte[] getSeed() { return seed; } /** * Returns the next pseudo-random sequence number. * * @return pseudo-random sequence number. */ public long next() { long r = current; current = rand.nextLong(); return r; } /** * Compares the specified argument with the current sequence * number. If they are equal, updates the current sequence * number to the next value. * * @param c sequence number to compare. * @return true if the argument equals the current sequence number, * otherwise false. */ public boolean compare( long c) { if( c != current) return false; current = rand.nextLong(); return true; } /** * Simple test program. */ public static void main (String[] args) { // Sequence t; // // t = new Sequence(null); // // byte[] j = ("abc").getBytes(); // t = new Sequence(j); Sequence s = new Sequence(); byte[] seed = s.getSeed(); long[] a = new long[10]; System.out.println( "\nUsing random seed"); for( int i = 0; i < 10; ++i) { a[i] = s.next(); System.out.println( a[i]); } s = new Sequence( seed); System.out.println( "\nUsing previous seed"); for( int i = 0; i < 10; ++i) System.out.println( s.next()); s = new Sequence( seed); System.out.println( "\nCheck compare..."); for( int i = 0; i < 10; ++i) System.out.println( s.compare(a[i])); } }