// Copyright 1997 The Open Group Research Institute.  All rights reserved.

package krb5.lib.crypto;

//XXX this class should be replaced with one that uses a
//true random number generator

//XXX obviously this will have to go
import java.util.Random;

public class Confounder {
	private static long count = 0;
	private static long index = 0;
	private static long lastKeyTime = 0;
	private static Random rand = new Random();	
	private static byte[] buffer = new byte[16];

	private static synchronized void reinitialize() {
		long reinitializeTime = System.currentTimeMillis();
		rand.setSeed(lastKeyTime + reinitializeTime + count + index);
		count++;
		for (int i = 0; i < buffer.length; i++)
			buffer[i] = (byte)rand.nextInt();
		//do an MD5 checksum on buffer here
		MD5 md5 = new MD5();
		md5.Update(buffer, buffer.length);
		buffer = md5.Final();
	}

	public static synchronized byte[] bytes(int size) {
		lastKeyTime = System.currentTimeMillis();
		byte[] data = new byte[size];
		for (int i = 0; i < data.length; i++) {
			if ((index % buffer.length) == 0)
				reinitialize();
			data[i] = buffer[(int)(index % buffer.length)];
			index++;
		}
		return data;
	}

	public static synchronized int intValue() {
		byte[] data = Confounder.bytes(4);
		int result = 0;
		for (int i = 0; i < 4; i++)
			result += data[i] * (16 ^ i);
		return result;
	}

	public static synchronized long longValue() {
		byte[] data = Confounder.bytes(4);
		long result = 0;
		for (int i = 0; i < 8; i++)
			result += ((long)data[i]) * (16L ^ i);
		return result;
	}

}

