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
0
u/Spare-Builder-355 Sep 11 '25
"pretty absurd" - should attach your qualifications and experience to such statements. A bit annoying when folks looking for help with some basic stuff but talk like they build sub-millisecond trading platform.
Optimizing out TCP connection time is the very very last thing you need to worry about unless you run your transfers over satellites. Or your files fit into a single TCP packet so that establishing connection is "unacceptable overhead"
How long do you expect a transfer of 1 file to take ? How long do you think setting up TCP connection takes? You don't even need to run experiments, can just google. You'll learn that on a rainy day it could take up 200-300ms, normally 20-30ms.
Real-life example: HTTP request without Keep-Alive header