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 keystore using keytool. I can then access the keystore using java code, obtain the certificate i added to the keystore and connect to the server.
I now however want to implement even the process of getting the certificate file and adding it to my keystore using java code and without using keytool or browser to get certificate.
Can someone please tell me how to approach this and what I need to do?
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.
I wrote small library ssl-utils-android to do so.
You can simply load any certificate by giving the filename from assets directory.
Usage:
OkHttpClient client = new OkHttpClient();
SSLContext sslContext = SslUtils.getSslContextForCertificateFile(context, "BPClass2RootCA-sha2.cer");
client.setSslSocketFactory(sslContext.getSocketFactory());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With