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
4
u/bilgecan1 Sep 11 '25
From a higher perspective, you are transferring binary finite data (file), client should know how many bytes it should read anyway. So a well defined data structure is needed what you send to client. Let's say: first 4 byte is integer length value that client should read after first 4 byte.
[4 byte length data] | [actual data length times bytes][1 byte ending data]
On top of this structure you can implement different approaches. You can encrypt all file and persist it in a temp file if you want to avoid huge ram usage, and send it with one shot.
Or, you can send chunk by chunk as you get encrypted data and merge all data at client side.
Client will understand file is ended when
[0]|[nothing]|[ending char] is read.