How can I use different certificates on specific connections?

后端 未结 5 2094
星月不相逢
星月不相逢 2020-11-22 01:22

A module I\'m adding to our large Java application has to converse with another company\'s SSL-secured website. The problem is that the site uses a self-signed certificate.

5条回答
  •  猫巷女王i
    2020-11-22 01:50

    Create an SSLSocket factory yourself, and set it on the HttpsURLConnection before connecting.

    ...
    HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
    conn.setSSLSocketFactory(sslFactory);
    conn.setMethod("POST");
    ...
    

    You'll want to create one SSLSocketFactory and keep it around. Here's a sketch of how to initialize it:

    /* Load the keyStore that includes self-signed cert as a "trusted" entry. */
    KeyStore keyStore = ... 
    TrustManagerFactory tmf = 
      TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keyStore);
    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(null, tmf.getTrustManagers(), null);
    sslFactory = ctx.getSocketFactory();
    

    If you need help creating the key store, please comment.


    Here's an example of loading the key store:

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(trustStore, trustStorePassword);
    trustStore.close();
    

    To create the key store with a PEM format certificate, you can write your own code using CertificateFactory, or just import it with keytool from the JDK (keytool won't work for a "key entry", but is just fine for a "trusted entry").

    keytool -import -file selfsigned.pem -alias server -keystore server.jks
    

提交回复
热议问题