简体   繁体   中英

Create SSLContext from private key and cer files

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.

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!

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>6.1.1</version>
</dependency>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM