Browse Source

Added padded streams

crypto
Thomas Johnson 3 years ago
parent
commit
0fa0d6aba6
  1. 33
      crypto/PaddedInputStream.java
  2. 46
      crypto/PaddedOutputStream.java

33
crypto/PaddedInputStream.java

@ -0,0 +1,33 @@
package crypto;
import java.io.IOException;
import java.io.InputStream;
public class PaddedInputStream extends InputStream
{
private int length;
private int remaining;
private byte buffer[];
private InputStream underlying;
public PaddedInputStream(InputStream underlying, int length)
{
this.underlying = underlying;
this.length = length;
this.remaining = 0;
this.buffer = new byte[length];
}
@Override
public int read() throws IOException
{
if (remaining == 0)
{
underlying.read(buffer, 0, length);
remaining = length - Byte.toUnsignedInt(buffer[length - 1]);
return read();
}
remaining -= 1;
return buffer[remaining];
}
}

46
crypto/PaddedOutputStream.java

@ -0,0 +1,46 @@
package crypto;
import java.io.IOException;
import java.io.OutputStream;
public class PaddedOutputStream extends OutputStream
{
private byte length;
private byte accumulated;
private byte buffer[];
private OutputStream underlying;
public PaddedOutputStream(OutputStream underlying, byte length)
{
this.underlying = underlying;
this.length = length;
this.buffer = new byte[length - 1];
this.accumulated = 0;
}
@Override
public void write(int i) throws IOException
{
buffer[accumulated] = (byte) i;
accumulated += 1;
if (accumulated + 1 == length)
{
underlying.write(buffer);
underlying.write((byte) 1);
accumulated = 0;
}
}
@Override
public void flush() throws IOException
{
if (accumulated != 0) {
underlying.write(buffer, 0, accumulated);
for (int ii = 0; ii < length - accumulated; ii++) {
underlying.write(length - accumulated);
}
accumulated = 0;
underlying.flush();
}
}
}
Loading…
Cancel
Save