All Projects โ†’ Hakky54 โ†’ sslcontext-kickstart

Hakky54 / sslcontext-kickstart

Licence: Apache-2.0 license
๐Ÿ” A lightweight high level library for configuring a http client or server based on SSLContext or other properties such as TrustManager, KeyManager or Trusted Certificates to communicate over SSL TLS for one way authentication or two way authentication provided by the SSLFactory. Support for Java, Scala and Kotlin based clients with examples. Avโ€ฆ

Programming Languages

java
68154 projects - #9 most used programming language

Projects that are alternatives of or similar to sslcontext-kickstart

letsencrypt-www
Probably the easiest way to create | renew | deploy certificate
Stars: โœญ 27 (-90.85%)
Mutual labels:  tls, ssl, certificate, https
Acme client
Java ACME Client application
Stars: โœญ 77 (-73.9%)
Mutual labels:  tls, ssl, certificate, https
Mutual Tls Ssl
๐Ÿ” Tutorial of setting up Security for your API with one way authentication with TLS/SSL and mutual mutual authentication for a java based web server and a client with both Spring Boot. Different clients are provided such as Apache HttpClient, OkHttp, Spring RestTemplate, Spring WebFlux WebClient Jetty and Netty, the old and the new JDK HttpClient, the old and the new Jersey Client, Google HttpClient, Unirest, Retrofit, Feign, Methanol, vertx, Scala client Finagle, Featherbed, Dispatch Reboot, AsyncHttpClient, Sttp, Akka, Requests Scala, Http4s Blaze, Kotlin client Fuel, http4k, Kohttp and ktor. Also other server examples are available such as jersey with grizzly. Also gRPC examples are included
Stars: โœญ 163 (-44.75%)
Mutual labels:  tls, ssl, certificate, https
httpsbook
ใ€Šๆทฑๅ…ฅๆต…ๅ‡บHTTPS๏ผšไปŽๅŽŸ็†ๅˆฐๅฎžๆˆ˜ใ€‹ไปฃ็ ็คบไพ‹ใ€ๅ‹˜่ฏฏใ€ๅ้ฆˆใ€่ฎจ่ฎบ
Stars: โœญ 77 (-73.9%)
Mutual labels:  tls, ssl, https
Pem
Easy PEM file parsing in Python.
Stars: โœญ 122 (-58.64%)
Mutual labels:  tls, ssl, certificate
Certstrap
Tools to bootstrap CAs, certificate requests, and signed certificates.
Stars: โœญ 1,689 (+472.54%)
Mutual labels:  tls, ssl, certificate
Tls Inspector
Easily view and inspect X.509 certificates on your iOS device.
Stars: โœญ 92 (-68.81%)
Mutual labels:  tls, ssl, https
ssl-handshake
A command-line tool for testing SSL/TLS handshake latency, written in Go.
Stars: โœญ 41 (-86.1%)
Mutual labels:  tls, ssl, https
Acmetool
๐Ÿ”’ acmetool, an automatic certificate acquisition tool for ACME (Let's Encrypt)
Stars: โœญ 1,882 (+537.97%)
Mutual labels:  tls, ssl, certificate
tlstools
๐Ÿ” CLI tool to analyze, troubleshoot or inspect SSL certificates, requests or keys.
Stars: โœญ 45 (-84.75%)
Mutual labels:  tls, ssl, https
Ssl exporter
Exports Prometheus metrics for SSL certificates
Stars: โœญ 211 (-28.47%)
Mutual labels:  tls, ssl, certificate
Tlslite Ng
TLS implementation in pure python, focused on interoperability testing
Stars: โœญ 119 (-59.66%)
Mutual labels:  tls, ssl, https
Sslsplit
Transparent SSL/TLS interception
Stars: โœญ 1,371 (+364.75%)
Mutual labels:  tls, ssl, https
Aspnetcorecertificates
Certificate Manager in .NET Core for creating and using X509 certificates
Stars: โœญ 135 (-54.24%)
Mutual labels:  tls, ssl, certificate
Ssl Checker
Python script that collects SSL/TLS information from hosts
Stars: โœญ 94 (-68.14%)
Mutual labels:  tls, ssl, certificate
Cert
Cert is the Go tool to get TLS certificate information.
Stars: โœญ 166 (-43.73%)
Mutual labels:  tls, ssl, certificate
Badssl.com
๐Ÿ”’ Memorable site for testing clients against bad SSL configs.
Stars: โœญ 2,234 (+657.29%)
Mutual labels:  tls, ssl, https
docker-ssl-reverse-proxy
Easy-to-use auto-SSL reverse proxy as a Docker container based on Caddy and Letโ€™s Encrypt
Stars: โœญ 22 (-92.54%)
Mutual labels:  tls, ssl, https
Merecat
Small and made-easy HTTP/HTTPS server based on Jef Poskanzer's thttpd
Stars: โœญ 69 (-76.61%)
Mutual labels:  tls, ssl, https
tipi
Tipi - the All-in-one Web Server for Ruby Apps
Stars: โœญ 214 (-27.46%)
Mutual labels:  tls, ssl, https

Actions Status Security Rating Known Vulnerabilities Coverage Language grade: Java JDK compatibility: 8+ Apache2 license Maven Central javadoc Dependencies: none GitHub stars chart Join the chat at https://gitter.im/hakky54/sslcontext-kickstart

SonarCloud

SSLContext Kickstart ๐Ÿ” Tweet

Install library with:

Install with Maven

<dependency>
    <groupId>io.github.hakky54</groupId>
    <artifactId>sslcontext-kickstart</artifactId>
    <version>7.4.5</version>
</dependency>

Install with Gradle

implementation 'io.github.hakky54:sslcontext-kickstart:7.4.5'

Install with Gradle Kotlin DSL

implementation("io.github.hakky54:sslcontext-kickstart:7.4.5")

Install with Scala SBT

libraryDependencies += "io.github.hakky54" % "sslcontext-kickstart" % "7.4.5"

Install with Apache Ivy

<dependency org="io.github.hakky54" name="sslcontext-kickstart" rev="7.4.5" />

Table of contents

  1. Introduction
  2. Usage
  3. Additional mappers for specific libraries
  4. Tested HTTP Clients
  5. Contributing
  6. Contributors
  7. License

Introduction

Hey, hello there ๐Ÿ‘‹ Welcome, you are visitors I hope you will like this library โค๏ธ

SSLContext Kickstart is a library which provides a High-Level SSLFactory class for configuring a http client or a server to communicate over SSL/TLS for one way authentication or two-way authentication. It is designed to be as lightweight as possible by having minimized the external dependencies. The core library only depends on the SLF4J logging API.

History

As a Java developer I worked for different kinds of clients. Most of the time the application required to call other microservices within the organization or some other http servers. These requests needed to be secured, and therefore it was required to load the ssl materials into the http client. Each http client may require different input value to enable https requests, and therefore I couldn't just copy-paste my earlier configuration into the new project. The resulting configuration was in my opinion always verbose, not reusable, hard to test and hard to maintain.

As a developer you also need to know how to properly load your file into your application and consume it as a KeyStore instance. Therefore, you also need to understand how to properly create for example a KeyManager and a TrustManager for you SSLContext. The sslcontext-kickstart library is taking the responsibility of creating an instance of SSLContext from the provided arguments, and it will provide you all the ssl materials which are required to configure 40+ different Http Client for Java, Scala and Kotlin. I wanted the library to be as easy as possible to use for all developers to give them a kickstart when configuring their Http Client. So feel free to provide feedback or feature requests. The library also provides other utilities such as:

See the javadoc for all the options.

Acknowledgement

I would like to thank Cody A. Ray for his contribution to the community regarding loading multiple Keystores into the SSLContext. The limitation of the JDK is to only support one keystore for the KeyManagerFactory and only one keystore for the TrustManagerFactory. The code snippets which Cody has shared are now available within this library and can be found here: CompositeX509KeyManager and CompositeX509TrustManager

The original content can be found here:

Advantages:

  • No need for low-level SSLContext configuration anymore
  • No knowledge needed about SSLContext, TrustManager, TrustManagerFactory, KeyManager, KeyManagerFactory and how to create it.
  • Above classes will all be created with just providing an identity and a trust material
  • Load multiple identities/trustStores/keyManagers/trustManagers
  • Hot reload ssl material without need of restarting/recreating Http Client or Server

Definitions

  • Identity material: A KeyStore or KeyManager which holds the key pair also known as private and public key
  • Trust material: A KeyStore or TrustManager containing one or more certificates also known as public key. This KeyStore contains a list of trusted certificates
  • One way authentication (also known as one way tls, one way ssl): Https connection where the client validates the certificate of the counter party
  • Two way authentication (also known as two way tls, two way ssl, mutual authentication): Https connection where the client as well as the counter party validates the certificate, also known as mutual authentication

Usage

Basic example configuration

Example configuration with apache http client, or click here to view the other client configurations

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import nl.altindag.ssl.SSLFactory;

public class App {

    public static void main(String[] args) throws IOException, JSONException {
        SSLFactory sslFactory = SSLFactory.builder()
                .withDefaultTrustMaterial()
                .build();

        HttpClient httpClient = HttpClients.custom()
                .setSSLContext(sslFactory.getSslContext())
                .setSSLHostnameVerifier(sslFactory.getHostnameVerifier())
                .build();

        HttpGet request = new HttpGet("https://api.chucknorris.io/jokes/random");

        HttpResponse response = httpClient.execute(request);
        String chuckNorrisJoke = new JSONObject(EntityUtils.toString(response.getEntity())).getString("value");

        System.out.println(String.format("Received the following status code: %d", response.getStatusLine().getStatusCode()));
        System.out.println(String.format("Received the following joke: %s", chuckNorrisJoke));
    }

}

Response:

Received the following status code: 200
Received the following joke: If a black cat crosses your path, you have bad luck. If Chuck Norris crosses your path, it was nice knowing you.

Other possible configurations

Loading keystore and truststore from the classpath
SSLFactory.builder()
          .withIdentityMaterial("identity.jks", "password".toCharArray())
          .withTrustMaterial("truststore.jks", "password".toCharArray())
          .build();
Loading keystore and trust store from anywhere on the filesystem
SSLFactory.builder()
          .withIdentityMaterial(Paths.get("/path/to/your/identity.jks"), "password".toCharArray())
          .withTrustMaterial(Paths.get("/path/to/your/truststore.jks"), "password".toCharArray())
          .build();
Loading keystore and trust store from InputStream
InputStream keyStoreStream = ...
InputStream trustStoreStream = ...

SSLFactory.builder()
          .withIdentityMaterial(keyStoreStream, "password".toCharArray())
          .withTrustMaterial(trustStoreStream, "password".toCharArray())
          .build();
Loading trust material with OCSP options
Loading trust material with TrustStore and OCSP options from the classpath
CertPathBuilder certPathBuilder = CertPathBuilder.getInstance("PKIX");
PKIXRevocationChecker revocationChecker = (PKIXRevocationChecker) certPathBuilder.getRevocationChecker();
revocationChecker.setOptions(EnumSet.of(PKIXRevocationChecker.Option.NO_FALLBACK));

SSLFactory sslFactory = SSLFactory.builder()
        .withTrustMaterial("truststore.jks", "password".toCharArray(), trustStore -> {
            PKIXBuilderParameters pkixBuilderParameters = new PKIXBuilderParameters(trustStore, new X509CertSelector());
            pkixBuilderParameters.addCertPathChecker(revocationChecker);
            return new CertPathTrustManagerParameters(pkixBuilderParameters);
        })
        .build();
Loading trust material with TrustStore and OCSP options from the file system
CertPathBuilder certPathBuilder = CertPathBuilder.getInstance("PKIX");
PKIXRevocationChecker revocationChecker = (PKIXRevocationChecker) certPathBuilder.getRevocationChecker();
revocationChecker.setOptions(EnumSet.of(PKIXRevocationChecker.Option.NO_FALLBACK));

SSLFactory sslFactory = SSLFactory.builder()
        .withTrustMaterial(Paths.get("/path/to/your/truststore.jks"), "password".toCharArray(), trustStore -> {
            PKIXBuilderParameters pkixBuilderParameters = new PKIXBuilderParameters(trustStore, new X509CertSelector());
            pkixBuilderParameters.addCertPathChecker(revocationChecker);
            return new CertPathTrustManagerParameters(pkixBuilderParameters);
        })
        .build();
Loading trust material with TrustManager and OCSP options
X509ExtendedTrustManager trustManager = ...

CertPathBuilder certPathBuilder = CertPathBuilder.getInstance("PKIX");
PKIXRevocationChecker revocationChecker = (PKIXRevocationChecker) certPathBuilder.getRevocationChecker();
revocationChecker.setOptions(EnumSet.of(PKIXRevocationChecker.Option.NO_FALLBACK));

SSLFactory sslFactory = SSLFactory.builder()
        .withTrustMaterial(trustManager, trustStore -> {
            PKIXBuilderParameters pkixBuilderParameters = new PKIXBuilderParameters(trustStore, new X509CertSelector());
            pkixBuilderParameters.addCertPathChecker(revocationChecker);
            return new CertPathTrustManagerParameters(pkixBuilderParameters);
        })
        .build();
Loading trust material with certificates and OCSP options
List<Certificate> certificates = ...

CertPathBuilder certPathBuilder = CertPathBuilder.getInstance("PKIX");
PKIXRevocationChecker revocationChecker = (PKIXRevocationChecker) certPathBuilder.getRevocationChecker();
revocationChecker.setOptions(EnumSet.of(PKIXRevocationChecker.Option.NO_FALLBACK));

SSLFactory sslFactory = SSLFactory.builder()
        .withTrustMaterial(certificates, trustStore -> {
            PKIXBuilderParameters pkixBuilderParameters = new PKIXBuilderParameters(trustStore, new X509CertSelector());
            pkixBuilderParameters.addCertPathChecker(revocationChecker);
            return new CertPathTrustManagerParameters(pkixBuilderParameters);
        })
        .build();
Enhanceable trust validations

By default, the TrustManager ships with default validations to validate if the counterparty is trusted during the SSL Handshake. If needed the default behaviour can be overruled by custom validators. If a custom validator is specified and if the condition evaluates to true, then the certificate of the counterparty will be trusted. If the condition evaluates to false, than it will fall back to the default behaviour of the TrustManager.

SSLFactory.builder()
          .withDefaultTrustMaterial()
          .withTrustEnhancer((X509Certificate[] certificateChain, String authType) ->
                  certificateChain[0].getIssuerX500Principal().getName().equals("Foo")
                      && certificateChain[0].getSubjectX500Principal().getName().equals("Bar"))
          .build();

Chaining of multiple validators is possible with the following snippet:

ChainAndAuthTypeValidator validator = ((ChainAndAuthTypeValidator) 
        (certificateChain, authType) -> certificateChain[0].getIssuerX500Principal().getName().equals("Foo"))
        .and((certificateChain, authType) -> certificateChain[0].getSubjectX500Principal().getName().equals("Bar"))
        .and((certificateChain, authType) -> certificateChain[0].getIssuerX500Principal().getName().equals("MyCompany"))
        .or((certificateChain, authType) -> certificateChain[0].getIssuerX500Principal().getName().equals("TheirCompany"));

SSLFactory sslFactory = SSLFactory.builder()
        .withDefaultTrustMaterial()
        .withTrustEnhancer(validator)
        .build();

The method has overloaded methods, and it is recommended to apply similar validators to the overloaded methods. The signature of the methods are:

SSLFactory sslFactory = SSLFactory.builder()
        .withDefaultTrustMaterial()
        .withTrustEnhancer(((X509Certificate[] certificateChain, String authType) -> myConditionWhichReturnsBoolean))
        .withTrustEnhancer(((X509Certificate[] certificateChain, String authType, Socket socket) -> myConditionWhichReturnsBoolean))
        .withTrustEnhancer(((X509Certificate[] certificateChain, String authType, SSLEngine sslEngine) -> myConditionWhichReturnsBoolean))
        .build();
Trusting all certificates without validation, not recommended to use at production!
SSLFactory.builder()
          .withUnsafeTrustMaterial()
          .build();
Skip hostname validation
SSLFactory.builder()
          .withDefaultTrustMaterial()
          .withUnsafeHostnameVerifier()
          .build();
Loading JDK and OS trusted certificates
SSLFactory.builder()
          .withDefaultTrustMaterial()
          .withSystemTrustMaterial()
          .build();
Using specific protocols, ciphers with custom secure random and hostname verifier

If you are using java 11 or newer, than you are also able to use TLSv1.3 as encryption protocol by default.

SSLFactory.builder()
          .withDefaultTrustMaterial()
          .withProtocols("TLSv1.3", "TLSv1.2")
          .withCiphers("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384")
          .withHostnameVerifier(hostnameVerifier)
          .withSecureRandom(secureRandom)
          .build();
Support for using multiple identity materials and trust materials
SSLFactory.builder()
          .withIdentityMaterial("identity-1.jks", password)
          .withIdentityMaterial("identity-2.jks", password)
          .withIdentityMaterial("identity-3.jks", password)
          .withIdentityMaterial("identity-4.jks", password)
          .withTrustMaterial("truststore-1.jks", password)
          .withTrustMaterial("truststore-2.jks", password)
          .withTrustMaterial("truststore-3.jks", password)
          .withTrustMaterial("truststore-4.jks", password)
          .build();

In some use cases multiple identities can fail to work. If that happens please try to add the additional SSLFactory option of identity route. See here for more: Routing identity to specific host

Support for using X509ExtendedKeyManager and X509ExtendedTrustManager
X509ExtendedKeyManager keyManager = ...
X509ExtendedTrustManager trustManager = ...

SSLFactory.builder()
          .withIdentityMaterial(keyManager)
          .withTrustMaterial(trustManager)
          .build();
Using dummy identity and trust material

In some use cases it may be useful to use a dummy identity or trust material. An example use case would be to create a base SSLFactory with the dummies which can be swapped afterwords. See below for a refactored version of Support for swapping KeyManager and TrustManager at runtime.

SSLFactory baseSslFactory = SSLFactory.builder()
          .withDummyIdentityMaterial()
          .withDummyTrustMaterial()
          .withSwappableIdentityMaterial()
          .withSwappableTrustMaterial()
          .build();
          
HttpClient httpClient = HttpClient.newBuilder()
          .sslParameters(sslFactory.getSslParameters())
          .sslContext(sslFactory.getSslContext())
          .build()
          
Runnable sslUpdater = () -> {
    SSLFactory updatedSslFactory = SSLFactory.builder()
          .withIdentityMaterial(Paths.get("/path/to/your/identity.jks"), "password".toCharArray())
          .withTrustMaterial(Paths.get("/path/to/your/truststore.jks"), "password".toCharArray())
          .build();
    
    SSLFactoryUtils.reload(baseSslFactory, updatedSslFactory);
};

// initial update of ssl material to replace the dummies
sslUpdater.run();
   
// update ssl material every hour    
Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(sslUpdater, 1, 1, TimeUnit.HOURS);

HttpResponse<String> response = httpClient.send(aRequest, HttpResponse.BodyHandlers.ofString());
Support for using a single KeyStore which contains multiple keys with different passwords
KeyStore keyStore = ...
X509ExtendedKeyManager keyManager = KeyManagerUtils.createKeyManager(keyStore, Map.of(
        "foo","foo-password".toCharArray(),
        "bar","bar-password".toCharArray(),
        "lorum-ipsum","lorum-ipsum-password".toCharArray()
));

SSLFactory.builder()
          .withIdentityMaterial(keyManager)
          .withDefaultTrustMaterial()
          .build();
Support for using PrivateKey and Certificates
PrivateKey privateKey = ...
char[] privateKeyPassword = ...
Certificate[] certificateChain = ...

Certificate trustedCertificate = ...

SSLFactory.builder()
          .withIdentityMaterial(privateKey, privateKeyPassword, certificateChain)
          .withTrustMaterial(trustedCertificate)
          .build();
Support for reloading ssl at runtime

It is possible to reload or update the ssl configuration while already using it with your client or server without the need of restarting your application or recreating it with SSLFactory. The identity and trust material may expire at some point in time and needs to be replaced to be still functional. Restart of the application with a traditional setup is unavoidable and can result into a downtime for x amount of time. A restart is not needed when using the setup below. The below example is a high-level method of reloading the ssl configuration, if you prefer to use a low-level setup please have a look at the following example displayed here: Hot swap KeyManager and TrustManager at runtime.

SSLFactory baseSslFactory = SSLFactory.builder()
          .withDummyIdentityMaterial()
          .withDummyTrustMaterial()
          .withSwappableIdentityMaterial()
          .withSwappableTrustMaterial()
          .build();
          
HttpClient httpClient = HttpClient.newBuilder()
          .sslParameters(sslFactory.getSslParameters())
          .sslContext(sslFactory.getSslContext())
          .build()
          
Runnable sslUpdater = () -> {
    SSLFactory updatedSslFactory = SSLFactory.builder()
          .withIdentityMaterial(Paths.get("/path/to/your/identity.jks"), "password".toCharArray())
          .withTrustMaterial(Paths.get("/path/to/your/truststore.jks"), "password".toCharArray())
          .build();
    
    SSLFactoryUtils.reload(baseSslFactory, updatedSslFactory);
};

// initial update of ssl material to replace the dummies
sslUpdater.run();
   
// update ssl material every hour    
Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(sslUpdater, 1, 1, TimeUnit.HOURS);

HttpResponse<String> response = httpClient.send(aRequest, HttpResponse.BodyHandlers.ofString());

See here for a basic reference implementation for a server: GitHub - Instant SSL Reloading

Support for swapping KeyManager and TrustManager at runtime

It is possible to swap a KeyManager and TrustManager from a SSLContext, SSLSocketFactory and SSLServerSocketFactory while already using it within your client or server at runtime. This option will enable to refresh the identity and trust material of a server or client without the need of restarting your application or recreating it with SSLFactory. The identity and trust material may expire at some point in time and needs to be replaced to be still functional. Restart of the application with a traditional setup is unavoidable and can result into a downtime for x amount of time. A restart is not needed when using the setup below.

SSLFactory baseSslFactory = SSLFactory.builder()
          .withIdentityMaterial(Paths.get("/path/to/your/identity.jks"), "password".toCharArray())
          .withTrustMaterial(Paths.get("/path/to/your/truststore.jks"), "password".toCharArray())
          .withSwappableIdentityMaterial()
          .withSwappableTrustMaterial()
          .build();
          
HttpClient httpClient = HttpClient.newBuilder()
          .sslParameters(sslFactory.getSslParameters())
          .sslContext(sslFactory.getSslContext())
          .build()

// execute https request
HttpResponse<String> response = httpClient.send(aRequest, HttpResponse.BodyHandlers.ofString());

SSLFactory updatedSslFactory = SSLFactory.builder()
          .withIdentityMaterial(Paths.get("/path/to/your/identity.jks"), "password".toCharArray())
          .withTrustMaterial(Paths.get("/path/to/your/truststore.jks"), "password".toCharArray())
          .build();
          
// swap identity and trust materials and reuse existing http client
KeyManagerUtils.swapKeyManager(baseSslFactory.getKeyManager().get(), updatedSslFactory.getKeyManager().get());
TrustManagerUtils.swapTrustManager(baseSslFactory.getTrustManager().get(), updatedSslFactory.getTrustManager().get());

// Cleanup old ssl sessions by invalidating them all. Forces to use new ssl sessions which will be created by the swapped KeyManager/TrustManager
SSLSessionUtils.invalidateCaches(baseSslFactory.getSslContext());

HttpResponse<String> response = httpClient.send(aRequest, HttpResponse.BodyHandlers.ofString());

See here for a basic reference implementation for a server: GitHub - Instant SSL Reloading

Routing identity material to specific host

It may occur that the client is sending the wrong certificate to the server when using multiple identities. This will happen when the client certificate has insufficient information for the underlying ssl engine (the KeyManager) and therefore it cannot select the right certificate. Recreating the certificates can resolve this issue. However, if that is not possible you can provide an option to the engine to use a specific certificate for a given server. Below is an example setup for correctly routing the client identity based on the alias which can be found within the KeyStore file.

SSLFactory.builder()
          .withIdentityMaterial("identity-1.jks", password)
          .withIdentityMaterial("identity-2.jks", password)
          .withTrustMaterial("truststore.jks", password)
          .withIdentityRoute("client-alias-one", "https://localhost:8443/", "https://localhost:8453/")
          .withIdentityRoute("client-alias-two", "https://localhost:8463/", "https://localhost:8473/")
          .build();
Updating identity routes at runtime
SSLFactory sslFactory = SSLFactory.builder()
          .withIdentityMaterial("identity-1.jks", password)
          .withIdentityMaterial("identity-2.jks", password)
          .withTrustMaterial("truststore.jks", password)
          .withIdentityRoute("client-alias-one", "https://localhost:8443/", "https://localhost:8453/")
          .withIdentityRoute("client-alias-two", "https://localhost:8463/", "https://localhost:8473/")
          .build();

X509ExtendedKeyManager keyManager = sslFactory.getKeyManager().get()

// Add additional routes next to the existing ones
KeyManagerUtils.addIdentityRoute(keyManager, "client-alias-one", "https://localhost:8463/", "https://localhost:8473/")

// Override existing routes
KeyManagerUtils.overrideIdentityRoute(keyManager, "client-alias-two", "https://localhost:9463/", "https://localhost:9473/")
Managing ssl session
SSLFactory sslFactory = SSLFactory.builder()
          .withIdentityMaterial("identity.jks", "password".toCharArray())
          .withTrustMaterial("truststore.jks", "password".toCharArray())
          .withSessionTimeout(3600) // Amount of seconds until it will be invalidated
          .withSessionCacheSize(1024) // Amount of bytes until it will be invalidated
          .build();
          
SSLContext sslContext = sslFactory.getSslContext();
          
// Caches can be invalidated with the snippet below
SSLSessionUtils.invalidateCaches(sslContext);

// or any other option:
SSLSessionUtils.invalidateCachesBefore(
        sslContext,
        ZonedDateTime.of(LocalDateTime.of(2021, JANUARY, 1, 15, 55), ZoneOffset.UTC)
);

SSLSessionUtils.invalidateCachesAfter(
        sslContext,
        ZonedDateTime.of(LocalDateTime.of(2021, FEBRUARY, 10, 8, 14), ZoneOffset.UTC)
);

SSLSessionUtils.invalidateCachesBetween(
        sslContext,
        ZonedDateTime.now().minusHours(2),    // from
        ZonedDateTime.now()                   // up till
);
Extracting server certificates
Map<String, List<Certificate>> certificates = CertificateUtils.getCertificate(
            "https://github.com/", 
            "https://stackoverflow.com/", 
            "https://www.reddit.com/",
            "https://www.youtube.com/");
            
// or get the server certificates as pem format
Map<String, List<String>> certificatesAsPem = CertificateUtils.getCertificateAsPem(
            "https://github.com/", 
            "https://stackoverflow.com/", 
            "https://www.reddit.com/",
            "https://www.youtube.com/");

See here for a demo application: GitHub - Certificate Ripper

Using P7B or PKCS#7 Files

Support for using p7b formatted certificates and certificate-chain from classpath, any directory or as an InputStream. P7b file is a text file containing a -----BEGIN PKCS7----- as header, -----END PKCS7----- as footer and has a Base64 encoded data between it.

List<Certificate> certificates = CertificateUtils.loadCertificate("certificate.p7b");

SSLFactory.builder()
          .withTrustMaterial(certificates)
          .build();

Using DER Files

Support for using der formatted certificates and certificate-chain from classpath, any directory or as an InputStream. Der file is a binary form of a certificate. Commonly used extensions are .cer and crt.

List<Certificate> certificates = CertificateUtils.loadCertificate("certificate.cer");

SSLFactory.builder()
          .withTrustMaterial(certificates)
          .build();

Using PFX, P12 or PKCS#12 Files

PFX and p12 are both PKCS#12 type keystores which are supported.

SSLFactory.builder()
          .withIdentityMaterial("identity.p12", "password".toCharArray())
          .withTrustMaterial("truststore.p12", "password".toCharArray())
          .build();

Using PEM Files

Support for using pem formatted private key and certificates from classpath, any directory or as an InputStream. See PemUtilsShould for detailed usages. Add the dependency below to use this feature, it also includes the core features from the library such as SSLFactory.

<dependency>
    <groupId>io.github.hakky54</groupId>
    <artifactId>sslcontext-kickstart-for-pem</artifactId>
    <version>7.4.5</version>
</dependency>
Loading pem files from the classpath
X509ExtendedKeyManager keyManager = PemUtils.loadIdentityMaterial("certificate.pem", "private-key.pem");
X509ExtendedTrustManager trustManager = PemUtils.loadTrustMaterial("some-trusted-certificate.pem");

SSLFactory.builder()
          .withIdentityMaterial(keyManager)
          .withTrustMaterial(trustManager)
          .build();
Loading pem files from anywhere on the filesystem
X509ExtendedKeyManager keyManager = PemUtils.loadIdentityMaterial(Paths.get("/path/to/your/certificate.pem"), Paths.get("/path/to/your/"private-key.pem"));
X509ExtendedTrustManager trustManager = PemUtils.loadTrustMaterial(Paths.get("/path/to/your/"some-trusted-certificate.pem"));
Loading pem files from InputStream
InputStream privateKey = ...
InputStream certificate = ...
InputStream trustedCertificates = ...

X509ExtendedKeyManager keyManager = PemUtils.loadIdentityMaterial(certificate, privateKey);
X509ExtendedTrustManager trustManager = PemUtils.loadTrustMaterial(trustedCertificates);
Loading pem files from string content
String privateKey =
        "-----BEGIN ENCRYPTED PRIVATE KEY-----\n" +
        "MIIFHDBOBgkqhkiG9w0BBQ0wQTApBgkqhkiG9w0BBQwwHAQIy3Fposf+2ccCAggA\n" +
        "-----END ENCRYPTED PRIVATE KEY-----\n";

String certificate =
        "-----BEGIN CERTIFICATE-----\n" +
        "g0Y2YBH5v0xmi8sYU7weOcwynkjZARpUltBUQ0pWCF5uJsEB8uE8PPDD3c4=\n" +
        "-----END CERTIFICATE-----\n";

String trustedCertificates =
        "-----BEGIN CERTIFICATE-----\n" +
        "CC01zojqS10nGowxzOiqyB4m6wytmzf0QwjpMw==\n" +
        "-----END CERTIFICATE-----\n";

X509ExtendedKeyManager keyManager = PemUtils.parseIdentityMaterial(certificate, privateKey, "secret".toCharArray());
X509ExtendedTrustManager trustManager = PemUtils.parseTrustMaterial(trustedCertificates);
Loading encrypted pem files
X509ExtendedKeyManager keyManager = PemUtils.loadIdentityMaterial("certificate.pem", "private-key.pem", "secret".toCharArray());
Migrating from classic configuration

Below is an example of the classic configuration for enabling ssl for your application.

-Djavax.net.ssl.trustStore=/path/to/truststore.jks
-Djavax.net.ssl.trustStoreType=jks
-Djavax.net.ssl.trustStorePassword=changeit
-Djavax.net.ssl.trustStoreProvider=SunJSSE

-Djavax.net.ssl.keyStore=/path/to/keystore.jks
-Djavax.net.ssl.keyStoreType=jks
-Djavax.net.ssl.keyStorePassword=changeit
-Djavax.net.ssl.keyStoreProvider=SunJSSE

-Dhttps.protocols=TLSv1.3
-Dhttps.cipherSuites=TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384

SSLFactory can be used with these properties together with the existing properties with the following snippet:

SSLFactory sslFactory = SSLFactory.builder()
        .withSystemPropertyDerivedIdentityMaterial()
        .withSystemPropertyDerivedTrustMaterial()
        .withSystemPropertyDerivedProtocols()
        .withSystemPropertyDerivedCiphers()
        .build();

SSLContext.setDefault(sslFactory.getSslContext());

The SSLFactory returnable values can be supplied to the http client as shown here

Returnable values from the SSLFactory

The SSLFactory provides different kinds of returnable values, see below for all the options:

import nl.altindag.ssl.SSLFactory;
import nl.altindag.ssl.model.KeyStoreHolder;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509ExtendedKeyManager;
import javax.net.ssl.X509ExtendedTrustManager;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Optional;

public class App {

    public static void main(String[] args) {
        SSLFactory sslFactory = SSLFactory.builder()
                .withIdentityMaterial("keystore.p12", "secret".toCharArray(), "PKCS12")
                .withTrustMaterial("truststore.p12", "secret".toCharArray(), "PKCS12")
                .build();

        SSLContext sslContext = sslFactory.getSslContext();
        HostnameVerifier hostnameVerifier = sslFactory.getHostnameVerifier();
        Optional<X509ExtendedKeyManager> keyManager = sslFactory.getKeyManager();
        Optional<X509ExtendedTrustManager> trustManager = sslFactory.getTrustManager();
        Optional<KeyManagerFactory> keyManagerFactory = sslFactory.getKeyManagerFactory();
        Optional<TrustManagerFactory> trustManagerFactory = sslFactory.getTrustManagerFactory();
        List<X509Certificate> trustedCertificates = sslFactory.getTrustedCertificates();
        SSLSocketFactory sslSocketFactory = sslFactory.getSslSocketFactory();
        SSLServerSocketFactory sslServerSocketFactory = sslFactory.getSslServerSocketFactory();
        SSLEngine sslEngine = sslFactory.getSslEngine(host, port);
        SSLParameters sslParameters = sslFactory.getSslParameters();
        List<String> ciphers = sslFactory.getCiphers();
        List<String> protocols = sslFactory.getProtocols();
    }

}

Additional mappers for specific libraries

Some http clients relay on different ssl classes from third parties and require mapping from SSLFactory to those libraries. Below you will find the maven dependency which will provide the mapping and also the SSLFactory library. When using one of the below libraries, it is not required to also explicitly include sslcontext-kickstart into your project. The additional mappers for specific libraries below won't provide transitive dependencies on Netty, Jetty or Apache. This has been decided to prevent dependency hell on your side.

Netty

Some know http clients which relay on netty libraries are: Spring WebFlux WebClient Netty, Async Http Client and Dispatch Reboot Http Client.

<dependency>
    <groupId>io.github.hakky54</groupId>
    <artifactId>sslcontext-kickstart-for-netty</artifactId>
    <version>7.4.5</version>
</dependency>

Example setup for Spring WebClient with Netty:

import io.netty.handler.ssl.SslContext;
import nl.altindag.ssl.SSLFactory;
import nl.altindag.ssl.util.NettySslUtils;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;

import javax.net.ssl.SSLException;

public class App {
    
    public static void main(String[] args) throws SSLException {
        SSLFactory sslFactory = SSLFactory.builder()
                .withDefaultTrustMaterial()
                .build();

        SslContext sslContext = NettySslUtils.forClient(sslFactory).build();
        HttpClient httpClient = HttpClient.create()
                .secure(sslSpec -> sslSpec.sslContext(sslContext));

        WebClient webClient = WebClient.builder()
                .clientConnector(new ReactorClientHttpConnector(httpClient))
                .build();
    }

}

Jetty

<dependency>
    <groupId>io.github.hakky54</groupId>
    <artifactId>sslcontext-kickstart-for-jetty</artifactId>
    <version>7.4.5</version>
</dependency>

Example setup for Spring WebFlux WebClient Jetty:

import nl.altindag.ssl.SSLFactory;
import nl.altindag.ssl.util.JettySslUtils;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.springframework.http.client.reactive.JettyClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;

public class App {

    public static void main(String[] args) {
        SSLFactory sslFactory = SSLFactory.builder()
                .withDefaultTrustMaterial()
                .build();
        
        SslContextFactory.Client sslContextFactory = JettySslUtils.forClient(sslFactory);
        HttpClient httpClient = new HttpClient(sslContextFactory);

        WebClient webClient = WebClient.builder()
                .clientConnector(new JettyClientHttpConnector(httpClient))
                .build();
    }

}

Apache

Apache 4

Apache Http Client works with javax.net.ssl.SSLContext, so an additional mapping to their library is not required, see here. However it is still possible to configure the http client with their custom configuration class. you can find below an example configuration for that use case:

<dependency>
    <groupId>io.github.hakky54</groupId>
    <artifactId>sslcontext-kickstart-for-apache4</artifactId>
    <version>7.4.5</version>
</dependency>
import nl.altindag.ssl.SSLFactory;
import nl.altindag.ssl.util.Apache4SslUtils;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.impl.client.HttpClients;

public class App {

    public static void main(String[] args) {
        SSLFactory sslFactory = SSLFactory.builder()
                .withDefaultTrustMaterial()
                .build();

        LayeredConnectionSocketFactory socketFactory = Apache4SslUtils.toSocketFactory(sslFactory);

        HttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(socketFactory)
                .build();
    }

}
Apache 5
<dependency>
    <groupId>io.github.hakky54</groupId>
    <artifactId>sslcontext-kickstart-for-apache5</artifactId>
    <version>7.4.5</version>
</dependency>
import nl.altindag.ssl.SSLFactory;
import org.apache.hc.client5.http.classic.HttpClient;
import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager;
import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder;
import org.apache.hc.client5.http.socket.LayeredConnectionSocketFactory;
import nl.altindag.ssl.util.Apache5SslUtils;

class App {

    public static void main(String[] args) {
        SSLFactory sslFactory = SSLFactory.builder()
                .withDefaultTrustMaterial()
                .build();

        LayeredConnectionSocketFactory socketFactory = Apache5SslUtils.toSocketFactory(sslFactory);
        PoolingHttpClientConnectionManager connectionManager = PoolingHttpClientConnectionManagerBuilder.create()
                .setSSLSocketFactory(socketFactory)
                .build();

        HttpClient httpClient = HttpClients.custom()
                .setConnectionManager(connectionManager)
                .build();

        PoolingAsyncClientConnectionManager asyncConnectionManager = PoolingAsyncClientConnectionManagerBuilder.create()
                .setTlsStrategy(Apache5SslUtils.toTlsStrategy(sslFactory))
                .build();

        CloseableHttpAsyncClient httpAsyncClient = HttpAsyncClients.custom()
                .setConnectionManager(asyncConnectionManager)
                .build();
    }
    
}

Tested HTTP Clients

Below is a list of clients which have already been tested with examples, see in the ClientConfig class and the service directory for detailed configuration

Java

Kotlin

Scala

There is a github project available named Mutual-tls-ssl which provides a tutorial containing steps for setting up these four scenarios:

  • No security
  • One way authentication
  • Two way authentication
  • Two way authentication with trusting the Certificate Authority

It will also explain how to create KeyStores, Certificates, Certificate Signing Requests and how to implement it.

Contributing

There are plenty of ways to contribute to this project:

  • Give it a star
  • Share it with a Tweet
  • Join the Gitter room and leave a feedback or help with answering users questions
  • Submit a PR

Contributors โœจ

Thanks goes to these wonderful people (emoji key):


Laurynas

๐Ÿ’ป ๐Ÿšง

Philippe Charles

๐Ÿค”

Tadhg Pearson

๐Ÿ›

winster

๐Ÿค”

Pablo Lalloni

๐Ÿค”

Luis Miguel Ospina

๐Ÿ›

Jรฉrรฉmie Panzer

๐Ÿค”

patpatpat123

๐Ÿค” ๐Ÿ›

Cody A. Ray

๐Ÿ’ป

Benoit Tellier

๐Ÿ’ป

sal0max

๐Ÿ›

lhstack

๐Ÿ›

dasteg

๐Ÿค”

rymsha

๐Ÿค”

manbucy

๐Ÿ› ๐Ÿ’ป

This project follows the all-contributors specification. Contributions of any kind welcome!

License

FOSSA Status

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].