Create SSLContext from private key and cer files

4.1k views Asked by At

I have two files:

  • mycer.cer
  • mykey.key

I need to create a SslContext to connect to another server via SSL using Java. I'm trying to find out how I can create the SslContext object directly from those files.

This post may be duplicated, but I tried to find a clear explanation with an example to create the SslContext, but didn't find something clear.

2

There are 2 answers

0
A Paul On

Get a certificate in p12 format, as far I know you can not use cert file, there are utilities to do that (like openssl) or the source (from where you generated downloaded the certificate) can give you a p12 format.

openssl pkcs12 -export -in mycer.crt -inkey mykey.key -out mycer.p12 -name "mycer"

And then check the below url, it should contain the information you want.

Java HTTPS client certificate authentication

Hopefully it helps!

0
Hakan54 On

This question is already answered here: In Java, what is the simplest way to create an SSLContext with just a PEM file?

I have created a library for this use case to simplify the configuration. It uses bouncy castle under the covers. See below for the usage:

X509ExtendedKeyManager keyManager = PemUtils.loadIdentityMaterial("certificate-chain.cer", "mykey.key");
X509ExtendedTrustManager trustManager = PemUtils.loadTrustMaterial("mycer.cer");

SSLFactory sslFactory = SSLFactory.builder()
          .withIdentityMaterial(keyManager)
          .withTrustMaterial(trustManager)
          .build();

SSLContext sslContext = sslFactory.getSslContext();

To use the above setup you can use this library:

<dependency>
    <groupId>io.github.hakky54</groupId>
    <artifactId>sslcontext-kickstart-for-pem</artifactId>
    <version>8.0.0</version>
</dependency>