Opa114
Opa114

Reputation: 548

How to access the Java Certificate Store with Java?

I found out that Java has its own "Certificate Store" which is located in a file in the security-folder inside the lib-folder.

You could access this from the Java Control Panel -> Security -> Manage Certificates.

But I want to access them via Java-Code. Does someone have some information about this? How the certificates are stored inside the certificate-File? Is there a Java built-in way for this?

Upvotes: 2

Views: 23492

Answers (2)

sharpcodes
sharpcodes

Reputation: 143

We had to use certs through the code to make API calls to certain applications. We could not install the certs on the code container for some reasons. The API service provider gave us the .cer file.Apache HTTP client was used for this purpose

Start with first creating a file based keystore and loaded this .cer file onto it

keytool -import -alias joe -file <path>/file.cer -keystore <keystoreName> -storepass <password>

Then add the generated keystore file as a resource into the application and build your custom HTTPClient to use this keystore

import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.ssl.SSLContexts;
import javax.net.ssl.SSLContext;
import java.io.File;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
    
File file = new File( getClass( ).getClassLoader( )
            .getResource( "<pathToKeystoreFile>" ).getFile( ) );

SSLContext sslcontext = SSLContexts.custom( ).loadTrustMaterial( 
    file, 
    CERT_PASSWORD.toCharArray( ), 
    new TrustSelfSignedStrategy( ) ).build( );

SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
            sslcontext,
            new String[] { "TLSv1", "SSLv3", "TLSv1.1", "TLSv1.2" },
            null,
            SSLConnectionSocketFactory.getDefaultHostnameVerifier( ) );

CloseableHttpClient customClient;
customClient = HttpClients.custom( )
            .setSSLSocketFactory( sslsf )
            .build( );

Upvotes: 2

Related Questions