How can I use certificate authentication with HttpsURLConnection?

前端 未结 3 991
遥遥无期
遥遥无期 2020-12-13 21:39

I\'m trying to connect to an HTTPS URL, but I need to use client authentication with a certificate placed on my system by third party software.

I haven\'t the slight

3条回答
  •  粉色の甜心
    2020-12-13 22:19

    From what I remember from my last attempt of doing that, you can't use HttpsURLConnection. You can have a look to the Apache HttpClient library that has support for this.

    Here is a code sample giving an idea of the process:

    String server = "example.com";
    int port = 443;
    EasySSLProtocolSocketFactory psf = new EasySSLProtocolSocketFactory();
    InputStream is = readFile("/path/to/certificate");
    KeyMaterial km = new KeyMaterial(is, "certpasswd".toCharArray());
    easy.setKeyMaterial(km);
    
    Protocol proto = new Protocol("https", (ProtocolSocketFactory) psf, port);
    HttpClient httpclient = new HttpClient();
    httpclient.getHostConfiguration().setHost(server, port, proto);
    

    Edit (regarding Tom comment):

    Here are some thoughts on how you can obtain the certificates stored in the Windows key store:

    • You need to use the Sun Cryptography suite (ie, a Sun Java 6 JDK)
    • You can obtain the KeyStore like this: ks = KeyStore.getInstance("Windows-MY");
    • You can load it this way: ks.load(null, null);. The JVM will load the Windos keystore and take care of asking for the keystore password.
    • You can then navigate the keystore like any other keystore.

提交回复
热议问题