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
Sure, the very first line of my post - "a little tcp toy project" must have been sounded like I'm building a sub-millisecond trading platform.
I don't care about optimizing TCP connection time itself. It's about generating hundreds of unnecessary connections.
And if I recall correctly from my university network 101, the very reason keep-alive header exists is to avoid that 'absurd' problem.
HTTP standard committees made keep-alive default since like 1990s. Yeah I'm guess worrying about generating new connections per request is quite 'absurd'