如何在其他两种类型的流中使用套接字流 - Java

How to use Socket stream in two other types of Streams - Java

我正在尝试为 Java 实现 Diffie-Hellman 的握手。我有一个小问题,Diffie-Hellman 是通过客户端的 Socket 使用 DataInputStream 和 DataOutputStream 完成的,但是为了使用它的秘密 returns,我需要使用 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 关闭了数据流,但也关闭了套接字。因此,当我尝试使用 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
    }

所以这是我的问题:

所有这一切的简单答案是将密码流包裹在各自的数据流中。