10

我正在尝试向为我提供 .p12 文件的服务器执行请求,以便与其他服务建立安全连接,我正在执行以下操作以使用密钥设置 HttpClient:

SSLContext sslContext =SSLContextBuilder
                .create().loadKeyMaterial(ResourceUtils.getFile("classpath:keystore/file.p12"), "secret".toCharArray(), "secret".toCharArray())
                .build();

    return HttpClientBuilder
            .create()
            .setConnectionManager(connManager())
            .setSSLContext(sslContext)
            .setDefaultRequestConfig(requestConfig())
            .build();

当我使用OAuth2RestOperations执行请求时,我得到:

401 , Non existing certificate or invalid 
4

3 回答 3

5

我最近有类似的要求。这是我使用的代码:

    KeyStore clientStore = KeyStore.getInstance("PKCS12");
    try {
        clientStore.load(ResourceUtils.getFile("classpath:keystore/file.p12"), "secret".toCharArray());
    } catch (IOException e) {
        //handle exception
    }

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(clientStore, "secret".toCharArray());
    KeyManager[] kms = kmf.getKeyManagers();

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(kms, null, new SecureRandom());

    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext);

    HttpClientBuilder builder = HttpClientBuilder.create();
    return builder.setSSLSocketFactory(socketFactory).build();
于 2019-05-15T19:30:00.450 回答
0

在所有示例中,您需要调用loadKeyMaterial方法KeyStore

 public SSLContextBuilder loadKeyMaterial(KeyStore keystore,

使用文件路径加载 keyStore,例如:

keyStore = KeyStore.getInstance("PKCS12");
FileInputStream inputStream = new FileInputStream(new File(certPath));
keyStore.load(inputStream, certPassword.toCharArray());
于 2019-05-15T12:13:21.450 回答
0

我认为这实际上是一个重复的问题。

请参阅此问题的答案Java HTTPS client certificate authentication

于 2019-05-14T23:14:11.257 回答