Connect to a https site with a given p12 certificate

后端 未结 5 1338
無奈伤痛
無奈伤痛 2020-12-04 10:32

The server side gave me a .p12 certificate file which I\'ve clicked and installed on my machine and then I can access the HTTPS site through browse

5条回答
  •  暖寄归人
    2020-12-04 11:02

    In case you are using Spring, it could be reached by RestTemplate:

    public RestTemplate restTemplate() throws Exception {
        KeyStore clientStore = KeyStore.getInstance("PKCS12");
        InputStream resource = this.getClass().getClassLoader().getResourceAsStream("path_to_certificate.p12");
        clientStore.load(resource, "p12_password".toCharArray());
    
        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
        sslContextBuilder.setProtocol("TLS");
        sslContextBuilder.loadKeyMaterial(clientStore, "p12_password".toCharArray());
        sslContextBuilder.loadTrustMaterial(new TrustSelfSignedStrategy());
    
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build());
        CloseableHttpClient httpClient = HttpClients.custom()
            .setSSLSocketFactory(sslConnectionSocketFactory)
            .build();
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
        return new RestTemplate(requestFactory);
    }
    

提交回复
热议问题