01: package org.bouncycastle.crypto;
02:
03: /**
04: * a wrapper for block ciphers with a single byte block size, so that they
05: * can be treated like stream ciphers.
06: */
07: public class StreamBlockCipher implements StreamCipher {
08: private BlockCipher cipher;
09:
10: private byte[] oneByte = new byte[1];
11:
12: /**
13: * basic constructor.
14: *
15: * @param cipher the block cipher to be wrapped.
16: * @exception IllegalArgumentException if the cipher has a block size other than
17: * one.
18: */
19: public StreamBlockCipher(BlockCipher cipher) {
20: if (cipher.getBlockSize() != 1) {
21: throw new IllegalArgumentException(
22: "block cipher block size != 1.");
23: }
24:
25: this .cipher = cipher;
26: }
27:
28: /**
29: * initialise the underlying cipher.
30: *
31: * @param forEncryption true if we are setting up for encryption, false otherwise.
32: * @param params the necessary parameters for the underlying cipher to be initialised.
33: */
34: public void init(boolean forEncryption, CipherParameters params) {
35: cipher.init(forEncryption, params);
36: }
37:
38: /**
39: * return the name of the algorithm we are wrapping.
40: *
41: * @return the name of the algorithm we are wrapping.
42: */
43: public String getAlgorithmName() {
44: return cipher.getAlgorithmName();
45: }
46:
47: /**
48: * encrypt/decrypt a single byte returning the result.
49: *
50: * @param in the byte to be processed.
51: * @return the result of processing the input byte.
52: */
53: public byte returnByte(byte in) {
54: oneByte[0] = in;
55:
56: cipher.processBlock(oneByte, 0, oneByte, 0);
57:
58: return oneByte[0];
59: }
60:
61: /**
62: * process a block of bytes from in putting the result into out.
63: *
64: * @param in the input byte array.
65: * @param inOff the offset into the in array where the data to be processed starts.
66: * @param len the number of bytes to be processed.
67: * @param out the output buffer the processed bytes go into.
68: * @param outOff the offset into the output byte array the processed data stars at.
69: * @exception DataLengthException if the output buffer is too small.
70: */
71: public void processBytes(byte[] in, int inOff, int len, byte[] out,
72: int outOff) throws DataLengthException {
73: if (outOff + len > out.length) {
74: throw new DataLengthException(
75: "output buffer too small in processBytes()");
76: }
77:
78: for (int i = 0; i != len; i++) {
79: cipher.processBlock(in, inOff + i, out, outOff + i);
80: }
81: }
82:
83: /**
84: * reset the underlying cipher. This leaves it in the same state
85: * it was at after the last init (if there was one).
86: */
87: public void reset() {
88: cipher.reset();
89: }
90: }
|