Search code examples
javasslhttpscertificate

Java HttpsURLConnection call rest web service and apply certificate programmatically


I been trying to bind rest service for payment purposes. They give me certificate in p12 format and gave me instruction to convert it in pem format using OpenSSL library. Now I have these two files.

key.pem(-----BEGIN ENCRYPTED PRIVATE KEY-----)
cert.pem(-----BEGIN CERTIFICATE-----)

My goal is to call this rest service using HttpsURLConnection. As far as I know, I need to do following:

KeyStore, SSLContext and then apply into httpsCon.setSSLSocketFactory(context.getSocketFactory());

I was looking for different solution but could not find working solution. Can someone provide working example?


Solution

  • Here is code worked for me. Hope it helps someone

    public class Main {
    
        @Autowired
        ResourceLoader resourceLoader;
    
        private static void applyCertificateInformation(HttpsURLConnection con, String password) throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {
            KeyStore clientStore = KeyStore.getInstance("PKCS12");
            clientStore.load(resourceLoader.getResource("my-cert.p12").getInputStream(), password.toCharArray());
    
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(clientStore, password.toCharArray());
    
            KeyManager[] kms = kmf.getKeyManagers();
    
    
            TrustManager[] tms = new TrustManager[]{
                    new X509TrustManager() {
    
                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return null;
                        }
    
                        @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("TLSv1.2");
            sslContext.init(kms, tms, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
            con.setSSLSocketFactory(sslContext.getSocketFactory());
        }
    
    }