Hi!
Im currently struggeling with encryption of streams using
CipherInputStream and CipherOutputStream. For some reason, the last 8
bytes when reading encrypted data seem to be missing (see example
below). Anyone have any idea why this occurs??
public void testCipherStreams() throws Exception {
int count = 80;
byte[] key = new byte[]{1, 2, 3, 4, 5, 6, 7, 8};
Key serverEncKey =
SecretKeyFactory.getInstance("DES").generateSecret(new
DESKeySpec(key));
// Create Ciphers
Cipher encCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
encCipher.init(Cipher.ENCRYPT_MODE, serverEncKey);
Cipher decCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
decCipher.init(Cipher.DECRYPT_MODE, serverEncKey);
// Create encryption-stream
ByteArrayOutputStream output = new ByteArrayOutputStream();
OutputStream encryptedOutput = new CipherOutputStream(output,
encCipher);
// Create a random buffer
Random rand = new Random();
byte[] buf = new byte[count];
rand.nextBytes(buf);
// Run it through the stream
encryptedOutput.write(buf);
encryptedOutput.flush();
output.flush();
byte[] encrypted = output.toByteArray();
// Create decryption-stream
ByteArrayInputStream input = new ByteArrayInputStream(encrypted);
InputStream decryptedInput = new CipherInputStream(input,
decCipher);
// Get decrypted output
byte[] decrypted = new byte[count];
decryptedInput.read(decrypted);
// Compare!
for (int i=0; i < count; i++) {
assertEquals("byte " + i + " did not match", buf[i], decrypted[i]);
}
}
Thx =)
Dale King - 24 Jun 2005 23:49 GMT
> Hi!
>
[quoted text clipped - 45 lines]
> }
> }
A read into an array is not guaranteed to completely fill the array. It
can read as little as one byte. It is allowed to return whatever amount
is most convenient for the stream it is reading from. For an encrypted
stream that is very likely to be less than the entire array. It returns
a count of how many bytes it did read. I'd bet if you looked at the
return value you are reading less than the size of the array.

Signature
Dale King