java 建立sslsocket 使用.cer 文件

java establish sslsocket use .cer file

我是 Java 和 SSLSocket 的新手。我想使用指定的 .cer 文件在客户端建立 SSLSocket。我在 google 中搜索它,但没有找到好的解决方案。这是我的代码:

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    InputStream caInput = new BufferedInputStream(new FileInputStream("myCer.cer"));
    Certificate ca;
    try {
        ca = cf.generateCertificate(caInput);
        System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
    } finally {
        caInput.close();
    }

    // Create a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", ca);

    // Create a TrustManager that trusts the CAs in our KeyStore
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keyStore);

    // Create an SSLContext that uses our TrustManager
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, tmf.getTrustManagers(), null);

    SSLSocket sock = (SSLSocket)context.getSocketFactory().createSocket("...",21000); //"...": here I ignore the host name. The address and port is right.
    sock.setUseClientMode(true);
    if(sock.isConnected()) {
        System.out.println("Connected...");
    }
    else
    {
        System.out.println("Connect Fails...");
    }

    Login.pbLogin login = Login.pbLogin.newBuilder().setUserID("dbs")
                                    .setPassword("abcd1234")
                                    .setNewPassword("")
                                    .setClientVersion("1.0.0.0")
                                    .setRestarted(true)
                                    .build();


    OutputStream outputStream =sock.getOutputStream();
    byte[] b1=login.getClass().getSimpleName().getBytes("UTF-8");
    byte[] b2=login.toByteArray();

    byte[] bytes = ByteBuffer.allocate(4).putInt(b1.length + b2.length).array();
    outputStream.write(bytes);
    outputStream.write(b1);  //login.getClass().getSimpleName().getBytes("UTF-8")
    outputStream.write(b2);  //login.toByteArray()
    outputStream.flush();

    byte[] content = new byte[100];
    int bytesRead = -1;
    InputStream inputStream = sock.getInputStream();
    String str;

    while(( bytesRead = inputStream.read( content) ) != -1){
        System.out.println("OK ,receive.....");
       // str = new String(Arrays.copyOfRange(content,0,bytesRead), StandardCharsets.UTF_8);
        //System.out.println(str);
    }

我用TCPViewer看,SSLSocket是Established状态,但是执行outstream.write时,SSLsocket会变成Close_wait状态,导致异常:

Exception in thread "main" java.net.SocketException: Software caused connection abort: socket write error.

所以我无法将信息写入服务器并退出程序。估计是SSLSocket没有建立成功,但是Tcpviewer显示建立的比较早,而且是Connected状态(print "connected.")。但是当尝试写入输出流时,它将处于 Close_wait 状态。你能帮我解决一下吗?

然后今天找到原因了。代码没有问题,原因是服务器部分无法正确解析协议缓冲区(pblogin),导致异常,因此关闭套接字。结果状态会在close_wait.Since我找到原因了,希望自己能解决