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 
DuSant
  • 970
  • 12
  • 25

3 Answers3

5

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();
heisbrandon
  • 1,180
  • 7
  • 8
  • 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 – DuSant May 17 '19 at 13:06
0

I think this is actually a duplicate question.

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

hooknc
  • 4,854
  • 5
  • 31
  • 60
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());
Ori Marko
  • 56,308
  • 23
  • 131
  • 233