简体   繁体   中英

How to load a trust store file to below code in Spring Java

I'm having a working code to communicate with a server, but now a trust store file is added to server to authenticate. How to add trust store.jks file to the code below:

My Java code:

KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(new FileInputStream("/users/Documents/workspace/publickey.cert"),
                "password".toCharArray());
        SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
                new SSLContextBuilder()
                        .loadTrustMaterial(null, new TrustSelfSignedStrategy())
                        .loadKeyMaterial(keyStore, "changeit".toCharArray()).build());
        HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
        ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
                httpClient);
        RestTemplate restTemplate = new RestTemplate(requestFactory);

    ResponseEntity<String> result = restTemplate.exchange("url",  HttpMethod.GET, new HttpEntity<String>(), String.class);

Assuming you imported your .cert file correctly to the store.jks file, you can do something like this to load up the store.jks file (or continue to use the method you are currently using to load up a file).

KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream instream = classLoader.getResourceAsStream("store.jks");
keyStore.load(instream, "JKSpassword".toCharArray());
instream.close();

From there it is the same except when you loadTrustMaterial for the SSLContextBuilder

SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
    new SSLContextBuilder()
        .loadTrustMaterial(keyStore, new TrustSelfSignedStrategy()).build());

Hope this helps.

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