title: Java sending encrypted file over socket
body: <p>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.</p>
  
  <p>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.</p>
  
  <p>I figure these issues are related, but I'm at a loss how to fix them.</p>
  
  <p>Here's the code I'm using to send the file on the server side:</p>
  
  <pre><code>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();
  </code></pre>
  
  <p>And the code to receive it on the client side:</p>
  
  <pre><code>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();
  </code></pre>
  
  <p>Any pointers in the right direction would be super.</p>