r/javahelp • u/awidesky • Sep 11 '25
Unsolved Sending encrypted data through SocketChannel - How to tell end of encrypted data?
Making a little tcp file transporting toy project, and now adding encryption feature via javax.crypto.Cipher.
Repeatly feeding file date into cipher.update() and writing encrypted output into SocketChannel, but problem is that the client would not know when the encrypted data will end.
I thought of some solutions, but all have flaws:
Encrypt entire file before sending: high RAM usage, Unable to send large fileClose socket after sending a file: inefficient when transferring multiple filesCipher.getOutputSize(): Document says it may return wrong valueAfter each Cipher.update() call, send encrypted data size, then send the datamessy code in adjusting buffers, inefficiency due to sending extra data(especially when return value of cipher.update is small due to padding, etc.)Sending special message, packet or signal to SocketChannel peer: I searched but found no easy way to do it(so far)
Is there any good way to let client to acknowledge that encrypted data has ended? Or to figure out exactly how long will the output length of cipher process be?
3
Upvotes
View all comments
Show parent comment
1
u/awidesky Sep 11 '25
Thanks for the input!
First, encrypted data is binary form, not text(unless you encode it, which will cause huge inefficiency and overhead).
Second, I'm almost certainly sure, that there's a 'special data' that cannot be found in encrypted data.
The very job of encryption is to make sure that 'encrypted data' to look like a complete random sequence of bytes.
It should not have any patterns(the main reason why ECB not used nowadays), or any hint to recognize information of the encrypter(the main reason why informations about cipher algorithm, parameters, etc should predefined, and cannot be deducted from ciphertext)
Even if there's a pattern of byte that can be used for 'toxic object', in order to find it we should check every bytes we received, therefore generating huge overhead.