9

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.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Marwan Jaber
  • 611
  • 11
  • 27
  • Are you maybe search for this ? http://stackoverflow.com/questions/32433832/configuring-sslcontext-using-existing-ssl-key-certificate-pair-in-java-jsse-api?answertab=active#tab-top – marpme May 14 '17 at 16:12
  • The proposed answer by @Kyon is a valid answer. For conversion from CER/KEY to a JKS (Java KeyStore) I can recommend Portecle - a standalone GUI tool: http://portecle.sourceforge.net/ - it imports basically everything :) – Philip Helger May 16 '17 at 20:45
  • What is the content of those files? Which format do they have and which encoding? – Gustave May 17 '17 at 04:32
  • I assume mycer.cer should contain your own certificate and mykey.key the corresponding private key. By default, Java uses the "JKS" (Java Key Store format). If you want to stick with that, you probably will have to convert your material accordingly. There are a lot of (partly not properly specified) file formats around. – Gustave May 17 '17 at 04:40

2 Answers2

2

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>
Hakan54
  • 3,121
  • 1
  • 23
  • 37
1

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!

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
A Paul
  • 8,113
  • 3
  • 31
  • 61