Java client certificates over HTTPS/SSL

后端 未结 8 995
攒了一身酷
攒了一身酷 2020-11-22 13:46

I am using Java 6 and am trying to create an HttpsURLConnection against a remote server, using a client certificate.
The server is using an selfsigned root

8条回答
  •  执念已碎
    2020-11-22 14:29

    Finally solved it ;). Got a strong hint here (Gandalfs answer touched a bit on it as well). The missing links was (mostly) the first of the parameters below, and to some extent that I overlooked the difference between keystores and truststores.

    The self-signed server certificate must be imported into a truststore:

    keytool -import -alias gridserver -file gridserver.crt -storepass $PASS -keystore gridserver.keystore

    These properties need to be set (either on the commandline, or in code):

    -Djavax.net.ssl.keyStoreType=pkcs12
    -Djavax.net.ssl.trustStoreType=jks
    -Djavax.net.ssl.keyStore=clientcertificate.p12
    -Djavax.net.ssl.trustStore=gridserver.keystore
    -Djavax.net.debug=ssl # very verbose debug
    -Djavax.net.ssl.keyStorePassword=$PASS
    -Djavax.net.ssl.trustStorePassword=$PASS
    

    Working example code:

    SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    URL url = new URL("https://gridserver:3049/cgi-bin/ls.py");
    HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
    conn.setSSLSocketFactory(sslsocketfactory);
    InputStream inputstream = conn.getInputStream();
    InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
    BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
    
    String string = null;
    while ((string = bufferedreader.readLine()) != null) {
        System.out.println("Received " + string);
    }
    

提交回复
热议问题