简体   繁体   中英

java: load HTTPS url with client certificate

I installed a pkcs12 certificate and could load the url "httpsURL" on browser.

But my standalone java program is not able to do the same.

System.setProperty("javax.net.ssl.keyStore", "d:/keys2222/prince.p12");
System.setProperty("javax.net.ssl.keyStorePassword", "password");
URL url = new URL("httpsURL"); // URL is perfect
URLConnection con = url.openConnection(); // fails here

please help me

Since you are using a self-signed certificate the JVM is not trusting it, so https URLs don't work. You need to add it to JVM's keystore with the keytool see this article .

EDIT: Sorry, I forgot to mention that you need to specify JVMs default keystore cacerts . This article will show you how it is done.

Also note that your certificate must match your URL exactly .

The reason you're getting java.security.cert.CertificateException: No name matching localhost found is that the CN of the certificate does not match the hostname of the URL you're accessing the server by. So you either need to create a certificate with the correct CN , or you can write your own HostNameVerifier to ignore the problem. But if you do that, make sure you remove that code when you're done testing. This document specifies how you can do that:

javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(
    new javax.net.ssl.HostnameVerifier(){

        public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
            if (hostname.equals("theHostname")) {
                return true;
            }
            return false;
        }
    };
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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