10

I'm trying to execute requests to a server which provided me with a .p12 file in order to make secure connection with rest services, I'm doing the following in order to set the HttpClient with the key:

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

When I execute the request with OAuth2RestOperations I got:

401 , Non existing certificate or invalid 

3 Answers 3

5
+100

I recently had a similar requirement. Here is the code I used:

    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();
Sign up to request clarification or add additional context in comments.

1 Comment

Did you configure something in your computer? I have tested same code and It does not work, I'm checking the CN information included in the request, and I can't see the information of the key. It seems like the key is not taken locally
0

I think this is actually a duplicate question.

Please see this answer for this question Java HTTPS client certificate authentication.

Comments

0

In all examples you need to call loadKeyMaterial method with KeyStore

 public SSLContextBuilder loadKeyMaterial(KeyStore keystore,

Load the keyStore using file path, for example:

keyStore = KeyStore.getInstance("PKCS12");
FileInputStream inputStream = new FileInputStream(new File(certPath));
keyStore.load(inputStream, certPassword.toCharArray());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.