简体   繁体   中英

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?

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());
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM