001: package org.bouncycastle.util.test;
002:
003: import java.io.ByteArrayOutputStream;
004: import java.io.IOException;
005: import java.security.SecureRandom;
006:
007: public class FixedSecureRandom extends SecureRandom {
008: private byte[] _data;
009:
010: private int _index;
011: private int _intPad;
012:
013: public FixedSecureRandom(byte[] value) {
014: this (false, new byte[][] { value });
015: }
016:
017: public FixedSecureRandom(byte[][] values) {
018: this (false, values);
019: }
020:
021: /**
022: * Pad the data on integer boundaries. This is necessary for the classpath project's BigInteger
023: * implementation.
024: */
025: public FixedSecureRandom(boolean intPad, byte[] value) {
026: this (intPad, new byte[][] { value });
027: }
028:
029: /**
030: * Pad the data on integer boundaries. This is necessary for the classpath project's BigInteger
031: * implementation.
032: */
033: public FixedSecureRandom(boolean intPad, byte[][] values) {
034: ByteArrayOutputStream bOut = new ByteArrayOutputStream();
035:
036: for (int i = 0; i != values.length; i++) {
037: try {
038: bOut.write(values[i]);
039: } catch (IOException e) {
040: throw new IllegalArgumentException(
041: "can't save value array.");
042: }
043: }
044:
045: _data = bOut.toByteArray();
046:
047: if (intPad) {
048: _intPad = _data.length % 4;
049: }
050: }
051:
052: public void nextBytes(byte[] bytes) {
053: System.arraycopy(_data, _index, bytes, 0, bytes.length);
054:
055: _index += bytes.length;
056: }
057:
058: //
059: // classpath's implementation of SecureRandom doesn't currently go back to nextBytes
060: // when next is called. We can't override next as it's a final method.
061: //
062: public int nextInt() {
063: int val = 0;
064:
065: val |= nextValue() << 24;
066: val |= nextValue() << 16;
067:
068: if (_intPad == 2) {
069: _intPad--;
070: } else {
071: val |= nextValue() << 8;
072: }
073:
074: if (_intPad == 1) {
075: _intPad--;
076: } else {
077: val |= nextValue();
078: }
079:
080: return val;
081: }
082:
083: //
084: // classpath's implementation of SecureRandom doesn't currently go back to nextBytes
085: // when next is called. We can't override next as it's a final method.
086: //
087: public long nextLong() {
088: long val = 0;
089:
090: val |= (long) nextValue() << 56;
091: val |= (long) nextValue() << 48;
092: val |= (long) nextValue() << 40;
093: val |= (long) nextValue() << 32;
094: val |= (long) nextValue() << 24;
095: val |= (long) nextValue() << 16;
096: val |= (long) nextValue() << 8;
097: val |= (long) nextValue();
098:
099: return val;
100: }
101:
102: public boolean isExhausted() {
103: return _index == _data.length;
104: }
105:
106: private int nextValue() {
107: return _data[_index++] & 0xff;
108: }
109: }
|