Connect to a https site with a given p12 certificate

后端 未结 5 1342
無奈伤痛
無奈伤痛 2020-12-04 10:32

The server side gave me a .p12 certificate file which I\'ve clicked and installed on my machine and then I can access the HTTPS site through browse

5条回答
  •  时光说笑
    2020-12-04 10:56

    Adding this as an answer as I need more space to write.

    First, a question: Is the certificate signed by a trusted authority such as Verisign? If it's not, the truststore should have the CA Certificate (usually a .pem file) which makes the p12 cert 'valid'. The default java trust store contains most (if not all) of the CA certificates from the big companies, such as Verisign and Thawte.

    Also, you can test your app to connect to the secure server without coding the SSL configuration, but with some command line parameters, for example:

    java -Djavax.net.ssl.keyStore=[path_to_p12_cert] \
     -Djavax.net.ssl.keyStorePassword=[p12_password] \
     -Djavax.net.ssl.keyStoreType=PKCS12 \
     -Djavax.net.ssl.trustStore=[path_to_trust_store_with_CA_certificates] \
     -Djavax.net.ssl.trustStorePassword=[trust_store_password] \
     [MainClass]
    

    and then your code becomes just

    HttpsURLConnection con = (HttpsURLConnection) (new URL(urlString)).openConnection();
    con.connect();
    con.getInputStream();
    con.disconnect();
    

    If you feel masochistic, the JSSE ref guide is great fun.

提交回复
热议问题