Difference between a Java KeyStore and a TrustStore

By Steve Claridge on 2018-09-12.

A KeyStore is a file that contains certificates, is it often created using the keytool tool, which is bundled with Java itself. Keystores are the usual way to hold certificates for use in Java code.

A KeyStore can contain one or more certificates and those certificates can be in a number of different formats, which I won't be mentioning here.

Keystores and the certificates in them are used when making secure communications from your Java code, e.g. when making a REST call to an external API over HTTPS. When you make that API call over HTTPS the server you call will be presenting a certificate containing their public key and your code needs to determine whether it trusts that certificate or not.

Similar to the API call scenario above, you may be making calls to an external server over HTTPS where the external server also wants to verify that you are who you say you are and that they trust you too.

So there are two sides to certificates and keystores: identifying your application to external systems and trusting external systems.

We said earlier that a KeyStore was a file that contains certificates, that is true, but to add confusion the name KeyStore is also used to determine one of the types of certificate in the store. It is common to have one Keystore file to hold your application's certificate(s) that identify it to external systems and another to hold certificates of systems that you trust.

A TrustStore holds the certificates of external systems that you trust .

So a TrustStore is a KeyStore file, that contains the public keys/certificate of external hosts that you trust. When you make HTTPS calls in your Java code, the certificate presented by the external host will be checked that it is in your TrustStore, if it is not you will get an Exception.

A KeyStoreholds your application's certificates.

A KeyStore is also a file of type KeyStore (!) and it holds public/private key pairs for certificates that identify your application during HTTPS calls.

Configuring stores

You can load and use Keystores yourself in code, for example:

KeyStore ks = KeyStore.getInstance( "JKS" );
InputStream s = new FileInputStream( filePathToKeyStore );
ks.load( s, keystorePasswordCharArray );

But it is also very common to specify your keystores as arguments when starting your app:



KeyStores are encrypted files and require a password to be accessed. If you use keytool to create a KeyStore you have to set a password for the store, you will also need to specify the password when reading keys/certificates from them, either via code or application arguments.