Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java sending encrypted file over socket

I've been trying to write a small file server. I got it to the point where a file transfer's just fine, but now that I've tried to add encryption strange things are happening. I'm trying to use cipher input/output streams to send the file using DES encryption. The file seems to be transferred completely by the server, but I can't get the client to receive it properly.

No matter what sort of file I transfer, the client never leaves the loop I'm using to receive the file. Even so, I've managed to receive .pdf and .doc files, neither of which seem to have any errors, and open perfectly. When I send an image though, the end doesn't seem to go through properly. The image opens, but the end never displays, just a greyed-out area instead.

I figure these issues are related, but I'm at a loss how to fix them.

Here's the code I'm using to send the file on the server side:

Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
CipherOutputStream cipherOut = new CipherOutputStream(outToClient, cipher);
byte[] fileBuffer = new byte[BUFFER_SIZE];
InputStream fileReader = new BufferedInputStream(new FileInputStream(aFile));
int bytesRead;
while((bytesRead = fileReader.read(fileBuffer)) != EOF){
    cipherOut.write(fileBuffer, 0, bytesRead);
}
cipherOut.flush();

And the code to receive it on the client side:

Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, serverPublicKey);
CipherInputStream cipherIn = new CipherInputStream(inFromServer, cipher);

byte[] fileBuffer = new byte[BUFFER_SIZE];
FileOutputStream fileWriter = new FileOutputStream(newFileName);
int bytesRead;
while((bytesRead = cipherIn.read(fileBuffer)) != EOF){
    fileWriter.write(fileBuffer, 0, bytesRead);
}
fileWriter.flush();
fileWriter.close();

Any pointers in the right direction would be super.

like image 938
charlemagne Avatar asked Oct 12 '22 00:10

charlemagne


2 Answers

  while((bytesRead = cipherIn.read(fileBuffer)) != EOF){

Is just going to keep reading until the number of 'bytesRead' gives you EOF, but that's not going to happen because you're not closing the socket(at least not that I can see if your code) on the other end.

I see

cipherOut.flush() ;

but that's not going to close the socket. If it's just 'falling out of scope' it won't be closed until the garbage collector reaps the object.

like image 177
Andrew Avatar answered Nov 15 '22 10:11

Andrew


you don't close the CipherOutputStream server side

with block cyphers a flush might cause some bytes not to be send until the block is filled or a close is executed which will cause the padding to come in effect and will allow the receiver to find the EOF

like image 44
ratchet freak Avatar answered Nov 15 '22 09:11

ratchet freak