Using .p12 file to execute request to rest server

2.3k views Asked by At

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

There are 3 answers

1
heisbrandon On BEST ANSWER

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();
0
hooknc On

I think this is actually a duplicate question.

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

0
Ori Marko On

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