繁体   English   中英

Java通过套接字发送加密文件

[英]Java sending encrypted file over socket

我一直在尝试编写一个小文件服务器。 我得到了文件传输的好处,但现在我已经尝试添加加密奇怪的事情正在发生。 我正在尝试使用密码输入/输出流来使用DES加密来发送文件。 该文件似乎完全由服务器传输,但我无法让客户端正确接收它。

无论我传输什么类型的文件,客户端都不会离开我用来接收文件的循环。 即便如此,我还是设法收到.pdf和.doc文件,这些文件似乎都没有任何错误,并且完全打开。 当我发送图像时,结果似乎没有正确通过。 图像打开,但结束永远不会显示,只是一个灰色的区域。

我认为这些问题是相关的,但我不知道如何修复它们。

这是我用来在服务器端发送文件的代码:

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();

以及在客户端接收它的代码:

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();

任何正确方向的指针都是超级的。

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

只是继续阅读,直到'bytesRead'的数量给你EOF,但这不会发生,因为你没有关闭套接字(至少不是我能看到你的代码)在另一端。

我懂了

cipherOut.flush() ;

但这不会关闭套接字。 如果它只是“超出范围”,它将不会被关闭,直到垃圾收集器收获对象。

你不要关闭CipherOutputStream服务器端

使用块密码,刷新可能会导致某些字节不被发送,直到块被填满或执行关闭将导致填充生效并允许接收器找到EOF

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM