Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using .p12 file to execute request to rest server

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 
like image 939
DuSant Avatar asked May 06 '19 22:05

DuSant


People also ask

What do I do with a P12 file?

It is used as a portable format for transferring personal private keys and other sensitive information. P12 files are used by various security and encryption programs. P12 keys store a private key that encrypts information in such a way that it can be decrypted only by the corresponding public key.

Can Java use P12?

If you want to attempt to code up the SSL configuration, you could use the P12 file given to you without having to convert it into a JKS. Also, you will need to use the private key in the P12, and not just the certificates that you copied into the JKS.


1 Answers

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();
like image 150
heisbrandon Avatar answered Sep 28 '22 22:09

heisbrandon