www.pudn.com > encryption.rar > CipherOutputStream.java
/*
Christoforos Pirillos @ Villanova University - May 1999
based on code from the book "Java Network Programming" by Hughes
*/
package encryption;
import java.io.*;
/**A filtered OutputStream that attaches to an existing OutputStream and
encrypts all data written to it. The Cipher that is used to perform the
encryption is specified in the constructor*/
public class CipherOutputStream extends FilterOutputStream {
protected ByteArrayOutputStream byteO;
protected OutputStream o;
protected Cipher c;
/**In the constructor we accept an OutputStream o over which we will send
encrypted data and a Cipher c with which we will perform the encryption.*/
public CipherOutputStream (OutputStream o, Cipher c) {
super (new ByteArrayOutputStream ());
byteO = (ByteArrayOutputStream) out;
this.o = o;
this.c = c;
}
public void flush () throws IOException {
writeEncrypted();
o.flush();
}
public void close () throws IOException {
flush();
o.close();
}
/**Encrypts and sends the data that we have buffered*/
protected void writeEncrypted () throws IOException {
if (byteO.size() > 0) {
byte[] b = byteO.toByteArray();
byteO.reset();
byte[] plain = new byte[b.length+4];
Crypt.intToBytes (plain.length, plain, 0);
System.arraycopy (b, 0, plain, 4, b.length);
byte[] cipher = c.encipher (plain);
o.write (cipher);
}
}
} /* end of class CipherOutputStream */