aAPT
dDebian
fFFmpeg
jJava
mMercurial: Usage
oOCaml
pPostgreSQL

Home Code Java

Java: SSL

Dealing with self-signed certificates

Use the dedicated key store

Get the certificate:

openssl s_client -showcerts -connect example.org:443 </dev/null 2>/dev/null | openssl x509 -outform PEM > out.crt

Import the certificate into key store file:

keytool -import -file out.crt -alias example.org -keystore store.jks

Use the key store in trust manager:

KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(new FileInputStream("/path/to/store.jks"), "PASSWORD".toCharArray());
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

Or use the downloaded certificate without key store file:

CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
Certificate certificate = certificateFactory.generateCertificate(new FileInputStream ("out.crt"));
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, null);
keyStore.setCertificateEntry("example.org", certificate);

Disable certificate validation completely

TrustManager[] trustManager = new TrustManager[] {
    new X509TrustManager() {
        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[0];
        }

        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {}

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {}
    }
};

SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustManager, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

Updating default key store with new certificate

Get the certificate with openssl s_client.

Import the certificate (default password is changeit):

keytool -import -alias example.com -cacerts -file /path/to/example.crt

or (JRE17+):

keytool -import -alias example.com -keystore /etc/ssl/certs/java/cacerts -file /path/to/example.crt