Commit 76f29304 authored by R.W.Majeed's avatar R.W.Majeed

fixed serious bugs in stream encrypt/decrypt code

parent ccd6a4ea
......@@ -26,7 +26,7 @@ public class DecryptingInputStream implements ReadableByteChannel {
public DecryptingInputStream(ReadableByteChannel in, String symmetricAlgorithm, int symmetricKeysize, String asymmetricCipher, Key asymmetricKey) throws GeneralSecurityException, IOException{
// use buffer
endOfStream = false;
buffer = ByteBuffer.allocate(1024*10);
buffer = ByteBuffer.allocate(1024*8);
in.read(buffer);
buffer.flip();
......@@ -64,7 +64,7 @@ public class DecryptingInputStream implements ReadableByteChannel {
@Override
public int read(ByteBuffer dst) throws IOException {
if( endOfStream )
return 0; // nothing to do
return -1; // nothing to do
int bytesRead=0;
if( buffer.hasRemaining() ){
......@@ -74,9 +74,11 @@ public class DecryptingInputStream implements ReadableByteChannel {
try {
if( bytesRead == -1 ){
endOfStream = true;
return cipher.doFinal(buffer, dst);
bytesRead = cipher.doFinal(buffer, dst);
return bytesRead;
}else{
return cipher.update(buffer, dst);
bytesRead = cipher.update(buffer, dst);
return bytesRead;
}
} catch (ShortBufferException | IllegalBlockSizeException | BadPaddingException e) {
throw new IOException(e);
......
......@@ -13,6 +13,13 @@ import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.ShortBufferException;
/**
* Wraps a WritableByteChannel with encryption.
* Closing the EncryptionOutputStream will close the underlying WritableByteChannel
* @author Raphael
*
*/
public class EncryptingOutputStream implements WritableByteChannel{
public static final int Version = 1;
private Cipher cipher;
......@@ -58,9 +65,11 @@ public class EncryptingOutputStream implements WritableByteChannel{
}
@Override
public void close() throws IOException {
buffer.flip();
if( buffer.hasRemaining() ){
out.write(buffer);
}
buffer.compact();
try {
out.write(ByteBuffer.wrap(cipher.doFinal()));
} catch (IllegalBlockSizeException | BadPaddingException e) {
......@@ -70,13 +79,19 @@ public class EncryptingOutputStream implements WritableByteChannel{
}
@Override
public int write(ByteBuffer src) throws IOException {
int processed = 0;
try {
int pos = src.position();
cipher.update(src, buffer);
processed = src.position() - pos;
} catch (ShortBufferException e) {
throw new IOException(e);
} finally {
}
if( buffer.position() != 0 ){
buffer.flip();
out.write(buffer);
buffer.compact();
}
return out.write(buffer);
return processed;
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment