如何将信任库文件加载到Spring Java中的代码下面

时间:2015-09-22 13:25:07

标签: java spring

我有一个工作代码与服务器通信,但现在信任存储文件被添加到服务器进行身份验证。如何将信任store.jks文件添加到以下代码中:

我的Java代码:

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

1 个答案:

答案 0 :(得分:2)

假设您已将.cert文件正确导入store.jks文件,您可以执行以下操作来加载store.jks文件(或继续使用您当前使用的方法加载文件。)

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

除非loadTrustMaterial

SSLContextBuilder,否则从那里开始是相同的
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
    new SSLContextBuilder()
        .loadTrustMaterial(keyStore, new TrustSelfSignedStrategy()).build());

希望这会有所帮助。