java建立sslsocket使用.cer文件

时间:2015-07-22 08:51:19

标签: java ssl ca java-security

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

    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显示它早期建立,并且处于连接状态(打印"连接。")。但是当尝试编写输出流时,它将处于Close_wait状态。你能帮我解决一下吗?

1 个答案:

答案 0 :(得分:0)

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