besnico
besnico

Reputation: 271

Alternative to closing a CipherInputStream

I'm having trouble because I need to close de CIS (or I won't get the last 16 bytes) but I can't because I'm using it over a socket:

cis = new CipherInputStream(new ObjectInputStream(socket.getInputStream));

(not exactly this, but it is how it's constructed).

So, if I close the socket, the program then tries to use it and I get an Exception for it...

Thanks a lot!

Upvotes: 1

Views: 780

Answers (1)

erickson
erickson

Reputation: 269667

You don't need to close a CipherInputStream to read the last block of data. That wouldn't make any sense.

What is happening is that your CipherInputStream has read all of the data in the final cipher text block, but is blocked in a read() call on the underlying stream. Detection of the end of the stream triggers the CipherInputStream to invoke doFinal() on its cipher instead of update(). Normally, this would happen because the end of the stream has been reached, in your case, because the socket was closed.

If you want to avoid closing the socket, you'll need to know the length of the cipher text. This might come from an HTTP header, or some other protocol that you create to transmit the encrypted data.

Extend FilterInputStream with a class that keeps track of how many bytes have been consumed (don't forget about the skip() method), and returns -1 from the read() method when the specified length of cipher text has been read. Override the close() method in your derived class so that it does not close the underlying stream.

Upvotes: 1

Related Questions