【发布时间】:2014-10-29 23:13:00
【问题描述】:
我正在发送(加密和发送文件)并通过套接字接收文件:
我的服务器代码:
private void send(OutputStream op,
FileInputStream filetoprocess, long l) throws Throwable {
Cipher ecipher;
byte[] inputBytes = new byte[(int) l];
filetoprocess.read(inputBytes);
byte[] ivBytes = "1234567812345678".getBytes();
DESKeySpec desKeySpec = new DESKeySpec(ivBytes);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey sKey = keyFactory.generateSecret(desKeySpec);
ecipher.init(Cipher.ENCRYPT_MODE, sKey);
byte[] outputBytes = ecipher.doFinal(inputBytes);
op.write(outputBytes);
op.flush();
System.out.println("File sent");
}
我的接收代码(在客户端):
private static void receive(InputStream ip, File fname,
PrintWriter output2) throws Throwable {
byte[] ivBytes = "1234567812345678".getBytes();
Cipher dcipher ;
DESKeySpec desKeySpec = new DESKeySpec(ivBytes);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey sKey = keyFactory.generateSecret(desKeySpec);
dcipher = Cipher.getInstance("DES");
dcipher.init(Cipher.DECRYPT_MODE, sKey);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = ip.read(buffer)) != -1)
{
out.write(buffer, 0, length);
}
byte[] result = out.toByteArray();
byte[] outputBytes = dcipher.doFinal(result);
FileOutputStream outputStream = new FileOutputStream(fname);
outputStream.write(outputBytes);
outputStream.close();
System.out.println("File received");
}
文件没有在客户端接收没有异常或什么都没有。客户就到此为止了。
我在这里做错了什么?我已经尝试过 Cipher O/I 流。但我的问题是加密时我需要关闭 CipherOutputStream 否则文件没有在客户端接收。发送文件后我需要收到客户端的确认,因为我正在关闭服务器中的 CipherOutputStream,它没有收到来自客户端的消息。它正在抛出 Socket 关闭异常。
所以我做了一个不同的版本(给出的代码)。但这也行不通。请帮我解决一下这个。
【问题讨论】:
-
“客户端停在这里”,这里到底是哪里?我复制/粘贴您的代码,它包含错误,服务器代码中的密码和客户端代码中的密码无法解析。一个想法:尝试不加密发送文件,成功后再加密。
-
你能告诉我什么错误吗?我只需要以加密形式发送。
-
是的,同意你的看法。我给了你解决问题的想法,首先尝试发送文件,一旦你得到正确的文件然后尝试加密它。错误在服务器代码中:
ecipher.init(Cipher.ENCRYPT_MODE, sKey);变量ecipher无法解析,在客户端代码中:dcipher.init(Cipher.DECRYPT_MODE, sKey);变量dcipher无法解析。 -
我刚刚添加了它们。它们是在函数外部声明的。
标签: java sockets encryption