简体   繁体   English

带证书的SSL连接

[英]SSL connection with certificate

I would like to replicate the following Python code into an equivalent in Java: 我想将以下Python代码复制到Java中的等效代码中:

import socket, ssl, pprint

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssl_sock = ssl.wrap_socket(s,
                           ca_certs="server.crt",
                           cert_reqs=ssl.CERT_REQUIRED)

ssl_sock.connect(('localhost', 10023))   
ssl_sock.write("boo!")

if False:
    data = ssl_sock.read()
    ssl_sock.close()

I came up with the following code (which is not working) but I still have two questions: 我想出了以下代码(无法正常工作),但仍然有两个问题:

abstract class Connection extends AsyncTask<String, Void, String> {


    boolean Connect(){
        try
        {
           SSLSocketFactory factory=(SSLSocketFactory) SSLSocketFactory.getDefault();
            SSLSocket mySSLSocket=(SSLSocket) factory.createSocket("localhost", 10023);

            DataOutputStream myOutPutStream = new DataOutputStream(mySSLSocket.getOutputStream());
            myOutPutStream.writeBytes("Hello World!");

            myOutPutStream.close();
            mySSLSocket.close();

            return true;

        }
        catch(Exception e)
        {
            return false;
        }

    }

}

By executing the code I get the following Java Error: 通过执行代码,我得到以下Java错误:

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
  1. Where do I save the certificate in my Android Application Project (Android Studio)? 证书在Android应用程序项目(Android Studio)中的哪里保存?

  2. What is the equivalent for the code below in Java? Java下面的代码等效于什么?

    ssl_sock = ssl.wrap_socket(s, ca_certs="server.crt", cert_reqs=ssl.CERT_REQUIRED) ssl_sock = ssl.wrap_socket(s,ca_certs =“ server.crt”,cert_reqs = ssl.CERT_REQUIRED)

Try -Djavax.net.ssl.trustStore=/path/to/keystore , where '/path/to/keystore' is the absolute file path of the alternative keystore. 尝试-Djavax.net.ssl.trustStore=/path/to/keystore ,其中“ / path / to / keystore”是备用密钥库的绝对文件路径。

This needs to be a VM option for running your code / project. 这必须是用于运行代码/项目的VM选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM