我正在尝试为Java实现Diffie-Hellman的握手。我有一个小问题,Diffie-Hellman是使用DataInputStream和DataOutputStream与客户端的Socket完成的,但是为了使用它返回的秘密,我需要使用CipherStream。所以我在套接字上使用CipherStream和DataStream。
public byte[] DHHandshake(Socket s){
byte[] secret = null;
try (DataOutputStream out = new DataOutputStream(s.getOutputStream())){
try(DataInputStream in = new DataInputStream(s.getInputStream())){
//Crear llave pública y privada en el cliente.
KeyPairGenerator kpg = KeyPairGenerator.getInstance(PROTOCOL);
kpg.initialize(Skip.sDHparameterSpec);
KeyPair keyPair = kpg.generateKeyPair();
//Envía llave pública del cliente al servidor
byte[] keyBytes = keyPair.getPublic().getEncoded();
out.writeInt(keyBytes.length);
out.write(keyBytes);
//Recibe llave pública del servidor
keyBytes = new byte[in.readInt()];
in.readFully(keyBytes);
KeyFactory kf = KeyFactory.getInstance(PROTOCOL);
X509EncodedKeySpec x509Spec = new X509EncodedKeySpec(keyBytes);
PublicKey theirPublicKey = kf.generatePublic(x509Spec);
//Llave pública servidor + llave privada cliente = llave compartida.
KeyAgreement ka = KeyAgreement.getInstance(PROTOCOL) ;
ka.init(keyPair.getPrivate());
ka.doPhase(theirPublicKey, true);
secret = ka.generateSecret();
}
}catch(Exception e) {
e.printStackTrace();
}
return secret;
}
try-with-resources关闭了数据流,但也关闭了Socket。因此,当我尝试使用在DiffieHellman中返回的秘密使用CipherStream发送文件时,它会抛出一个异常,说明套接字已关闭:
private void receiveFile(Socket s, byte[] secret){
try(FileOutputStream fileWriter = new FileOutputStream(FILE)){
Cipher cipher = Cipher.getInstance(ALGORITHM + "/ECB/PKCS5PADDING");
SecretKeySpec keySpec = new SecretKeySpec(secret, ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
try(CipherInputStream cipherIn = new CipherInputStream(s.getInputStream(), cipher)){
byte[] fileBuffer = new byte[1024];
int len;
while ((len = cipherIn.read(fileBuffer)) >= 0)
fileWriter.write(fileBuffer, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
}
//TODO checkMD5
}
所以这是我的问题:
如果我不关闭DataStream,则可以重新使用SocketStream来发送数据。这会不会损坏SocketStream,因为DataStream和CipherStream同时使用它?
有没有办法在不关闭SocketStream的情况下关闭DataStream?
答案 0 :(得分:1)
所有这一切的简单答案是将密码流包装在各自的数据流周围。