Adding certificate to keystore using java code

前端 未结 3 1874
花落未央
花落未央 2020-12-23 10:45

I\'m trying to establish a https connection using the server\'s .cer certificate file. I am able to manually get the certificate file using a browser and put it into the key

3条回答
  •  一整个雨季
    2020-12-23 11:04

    Edit: This seems to do exactly what you want.

    Using the following code it is possible to add a trust store during runtime.

    import java.io.InputStream;
    import java.security.KeyStore;
    
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.TrustManagerFactory;
    
    public class SSLClasspathTrustStoreLoader {
        public static void setTrustStore(String trustStore, String password) throws Exception {
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509");
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            InputStream keystoreStream = SSLClasspathTrustStoreLoader.class.getResourceAsStream(trustStore);
            keystore.load(keystoreStream, password.toCharArray());
            trustManagerFactory.init(keystore);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustManagers, null);
            SSLContext.setDefault(sc);
        }
    }
    

    I used this code to establish a secure LDAP connection with an active directory server.

    This could also be usful, at the bottom there is a class, which is able to import a certificate during runtime.

提交回复
热议问题