package ssh;

import java.util.Random;
import java.math.BigInteger;

/**
 * This class implements a pool of random bits, and provides
 * access methods that are appropriate to the needs of this package.
 * 
 * @todo grab some actual randomness from the environment to keep the
 * entropy flowing.
 * @todo or better yet, replace with a call to the new JCE.
 * 
 * @author Jon Howell <jonh@cs.dartmouth.edu>
 * @rcs $Id: SshRandom.java,v 1.3 2000/05/26 06:17:34 jonh Exp $
 * @license This code is Copyright 1999 Jon Howell. It is available for
 * use under the GNU Public License, available at:
 * http://www.gnu.org/copyleft/gpl.html 
 */
public class SshRandom
	extends Random {

	public int nextByte() {
		// what a waste of 75% of our random bits!
		return (nextInt() & 0x0ff);
	}

	public int nextNonzeroByte() {
		int result;
		do {
			result = nextByte();
		} while (result == 0);
		return result;
	}

	public BigInteger newBigInteger(int size) {
		return newBigIntegerBits(size<<3);	// interpret arg 'size' in bytes
	}

	public BigInteger newBigIntegerBits(int size) {
		// size is in bits
		BigInteger b = new BigInteger("0");
		while (size>=32) {
			b = b.shiftLeft(32);
			b = b.or(BigInteger.valueOf((long) nextInt()).abs());
			size-=32;
		}
		while (size>=8) {
			b = b.shiftLeft(8);
			b = b.or(BigInteger.valueOf((long) nextByte()));
			size-=8;
		}
		if (size>=1) {
			b = b.shiftLeft(size);
			int mask = (1<<size) - 1;
			b = b.or(BigInteger.valueOf((long) (nextByte()&mask)));
			size-=size;
		}
		return b;
	}

	public byte[] newByteArray(int size) {
		byte[] b = new byte[size];		// size is in bytes
		for (int i=0; i<size; i++) {
			b[i] = (byte) nextByte();
		}
		return b;
	}
}
