Skip to content

Instantly share code, notes, and snippets.

@DrBrad
Created March 25, 2024 22:16
Show Gist options
  • Save DrBrad/014e96378ca5a07e5fd17bd74c0b406f to your computer and use it in GitHub Desktop.
Save DrBrad/014e96378ca5a07e5fd17bd74c0b406f to your computer and use it in GitHub Desktop.
Improved CipherInputStream & CipherOutputStream
import javax.crypto.Cipher;
import javax.crypto.NullCipher;
import javax.crypto.ShortBufferException;
import java.io.EOFException;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
public class CipherInputStream extends FilterInputStream {
private Cipher cipher;
public CipherInputStream(InputStream in){
this(in, new NullCipher());
}
public CipherInputStream(InputStream in, Cipher cipher){
super(in);
this.cipher = cipher;
}
public int read()throws IOException {
byte[] buf = new byte[1];
read(buf, 0, 1);
return buf[0];
}
public int read(byte[] buf)throws IOException {
return read(buf, 0, buf.length);
}
public int read(byte[] buf, int off, int len)throws IOException {
try{
int length = in.read(buf, off, len);
if(length > 0){
length = cipher.update(buf, 0, length, buf, 0);
}
return length;
}catch(ShortBufferException e){
return 0;
}
}
public void readFully(byte[] b, int off, int len)throws Exception {
if(len < 0){
throw new IndexOutOfBoundsException("Negative length: "+len);
}
while(len > 0){
int numread = read(b, off, len);
if(numread < 0){
throw new EOFException();
}
len -= numread;
off += numread;
}
}
}
import javax.crypto.Cipher;
import javax.crypto.NullCipher;
import java.io.*;
public class CipherOutputStream extends FilterOutputStream {
private Cipher cipher;
public CipherOutputStream(OutputStream out){
this(out, new NullCipher());
}
public CipherOutputStream(OutputStream out, Cipher cipher){
super(out);
this.cipher = cipher;
}
public void flush()throws IOException {
out.flush();
}
public void write(int value)throws IOException {
write(new byte[]{ (byte) value }, 0, 1);
}
public void write(byte[] buf)throws IOException {
write(buf, 0, buf.length);
}
public void write(byte[] buf, int off, int len)throws IOException {
byte[] crypted = cipher.update(buf, off, len);
out.write(crypted);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment