skip to content

In Java's JSSE, what do SSLContext, KeyManagerFactory and TrustManagerFactory each do, and how do you build an SSLContext from a keystore and a truststore?

level: juniorimportance: should knowfreq 42%

answer

  1. who am I, whom do I believe
  2. keystore holds keys, truststore holds anchors
  3. init, getKeyManagers, getTrustManagers
  4. each null means something different
  5. your truststore replaces the defaults

basics

~10 s

KeyManagerFactory turns a keystore into key managers that present your identity. TrustManagerFactory turns a truststore into trust managers that judge the peer's certificates. SSLContext.init combines both, then produces socket factories and SSLEngines.

solid answer

~40 s

`SSLContext` is JSSE's factory for `SSLSocketFactory`, `SSLServerSocketFactory` and `SSLEngine`, configured with key managers, trust managers and a random source. `KeyManagerFactory` loads a `KeyStore` holding your private key and certificate chain, so it answers who you are; `TrustManagerFactory` loads a `KeyStore` of certificates you trust, so it answers whom you believe. To build one: `kmf.init(keyStore, keyPassword)`, `tmf.init(trustStore)`, `SSLContext.getInstance("TLS")`, then `context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null)`. With the JDK's SunJSSE provider, `null` key managers mean no identity at all, `null` trust managers fall back to the default truststore, and a `null` random source uses a default `SecureRandom`. A truststore you pass replaces the defaults rather than adding to them.

code

java · 23 lines
java
import java.io.File;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

final class TlsContexts {
    static SSLContext build(File keyStore, char[] storePassword, char[] keyPassword,
                            File trustStore, char[] trustPassword)
            throws GeneralSecurityException, IOException {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(KeyStore.getInstance(keyStore, storePassword), keyPassword);

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(KeyStore.getInstance(trustStore, trustPassword));

        SSLContext context = SSLContext.getInstance("TLS");
        context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        return context;
    }
}

go deeper

for a junior

Recall which factory handles your own identity and which judges the peer, and the four calls that build a context from two stores.

for a middle

Explain what each null argument to init means with SunJSSE, why a passed truststore replaces the defaults, and why only the first trust manager counts.

for a senior

Show production habits: build the context once and share it for session reuse, keep key and store passwords straight, and set endpoint identification on raw sockets.

for a principal

Decide how a team distributes keystores and truststores, which code may build its own context versus use the default, and who owns trust anchors across services.

## The three classes **JSSE**, the Java Secure Socket Extension, is the part of the JDK that speaks TLS, in the package `javax.net.ssl`. Three classes do the setup: | Class | What it does | Question it answers | Built from | |---|---|---|---| | `KeyManagerFactory` | Produces `KeyManager` objects that choose and present your certificate | Who am I? | A `KeyStore` with private keys and their chains, plus the password that recovers the keys | | `TrustManagerFactory` | Produces `TrustManager` objects that decide whether a peer's certificates are acceptable | Whom do I believe? | A `KeyStore` holding trusted certificates | | `SSLContext` | Holds those managers and a random source, and is the factory for `SSLSocketFactory`, `SSLServerSocketFactory` and `SSLEngine` | How do I open secure connections? | The output of the other two | The socket factories suit blocking code that owns a socket. `SSLEngine` does the same TLS work without owning any transport, which is what non-blocking servers and the HTTP/1.1 and HTTP/2 connections of `java.net.http.HttpClient` build on. Both draw their keys, trust decisions and session caches from the same context. ## Keystore against truststore Both words describe how a file is used, not what it is: each is read through the same `KeyStore` class and can use the same format, such as PKCS12. A **keystore** holds your own private key with its certificate chain. A **truststore** holds the certificates you accept as starting points for validating others, called **trust anchors**, usually CA certificates. A server needs a keystore to prove who it is. A client needs a truststore to judge the server, and a keystore too only when the server asks for a client certificate, which is mutual TLS. One file can serve both roles, with a side effect: when a store holding a key entry is passed to `TrustManagerFactory`, the JDK also trusts the first certificate of that entry. The `KeyStore` API itself is covered with key generation and keystores. ## Building the context The steps run in this order, because each one consumes the output of the one before: 1. Load the keystore and call `KeyManagerFactory.init(keyStore, keyPassword)`. That password recovers the private keys, and it is separate from the one that opens the store, although PKCS12 files often use one value for both. 2. Load the truststore and call `TrustManagerFactory.init(trustStore)`. 3. Call `SSLContext.getInstance("TLS")`, then `init(kmf.getKeyManagers(), tmf.getTrustManagers(), null)`. 4. Use the context: `getSocketFactory()`, `getServerSocketFactory()`, `createSSLEngine()`, or hand it to a client with `HttpClient.newBuilder().sslContext(context)`. The factories' algorithm names come from `getDefaultAlgorithm()`. On JDK 27, as on 25, those return `SunX509` for key managers and `PKIX` for trust managers, set by the `ssl.KeyManagerFactory.algorithm` and `ssl.TrustManagerFactory.algorithm` security properties, and `getInstance("TLS")` enables `TLSv1.3` and `TLSv1.2`. Using an `SSLContext` before `init` throws `IllegalStateException`. ## What each null means `SSLContext.init` accepts `null` for any argument, and each means something different. With the JDK's SunJSSE provider: - `null` key managers give an empty key manager, so the context has no certificate to present. The `javax.net.ssl.keyStore` system property does not fill the gap. - `null` trust managers fall back to a default trust manager. It reads the file named by `javax.net.ssl.trustStore` or, when that property is unset, `lib/security/jssecacerts` under the Java home; if the chosen file cannot be read, it falls back to `lib/security/cacerts`. Validation stays on. - A `null` random source means a default `SecureRandom`. ## Mistakes that cost an afternoon - **Expecting your truststore to add to the defaults.** `tmf.init(myStore)` trusts what is in `myStore` and nothing else, so public CAs in `cacerts` stop working for that context. - **Passing two trust managers to combine them.** `init` uses only the first instance of each manager type in the array, so a second `X509TrustManager` is ignored. Merge the certificates into one store instead. - **A wrong key password.** `kmf.init` throws `UnrecoverableKeyException`, and the default `SunX509` factory uses the one password for every key entry in the store. - **Rebuilding the context per connection.** The client and server session caches live on the `SSLContext`, so a fresh one loses session resumption and repeats the key loading. - **Assuming the context checks host names.** It does not. A raw `SSLSocket` has no endpoint identification algorithm by default, so set `HTTPS` through `SSLParameters`; `java.net.http.HttpClient` sets it itself. - **Confusing it with `SSLContext.getDefault()`.** That context is built from the `javax.net.ssl.*` system properties and is ready to use; calling `init` on it throws `KeyManagementException`. How a trust manager judges a chain, and what its refusal looks like, is a question of its own.

  • What happens if a client calls context.init(null, trustManagers, null) and the server requires a client certificate?
    With SunJSSE, null key managers become an empty key manager, so the client sends no certificate and the server ends the handshake. Under TLS 1.3 the client's `startHandshake()` can return first, and the failure arrives on the first read as a `certificate_required` alert, so error handling around the handshake call alone misses it.
  • How do you trust both the JDK's public CAs and a private CA in one context?
    Passing two trust managers does not work, because only the first `X509TrustManager` in the array is used. Instead, initialise a factory with `init((KeyStore) null)` to get the defaults, copy its `getAcceptedIssuers()` into a new `KeyStore`, add the private CA, and initialise a second factory from that merged store.
  • What does SSLContext.getDefault() give you, and can you call init on it?
    It returns a ready-to-use context built from the `javax.net.ssl.keyStore`, `javax.net.ssl.trustStore` and related system properties. It needs no `init`, and calling `init` on it throws `KeyManagementException`. `SSLContext.setDefault` replaces it for every later caller in the JVM, so treat that as a process-wide change.

  • KeyManagerFactory decides which of the peer's certificates to trust.
  • TrustManagerFactory.init with your own store adds your CA to the JDK's default trusted CAs.
  • Passing null trust managers to SSLContext.init switches certificate checking off.
  • Putting two X509TrustManager objects in the array makes JSSE try each in turn.
  • Once an SSLContext is built, a raw SSLSocket from it checks the server's host name automatically.
  • A keystore and a truststore need different file formats.

SSLContext
Java 1.4
KeyManagerFactory
Java 1.4
TrustManagerFactory
Java 1.4
KeyStore.getInstance(File, char[])
Java 9

Assumes Java 27; the default algorithm names and enabled protocols described here are the same on JDK 25.

context