[英]How to use Socket stream in two other types of Streams - Java
我正在嘗試為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發送數據。 因為DataStream和CipherStream同時使用它,這不會損壞SocketStream嗎?
有沒有一種方法可以不關閉SocketStream而關閉DataStream?
所有這些的簡單答案是將密碼流包裝在各自的數據流周圍。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.