Exploring Java KeyStore & Keys
Via code
What is a KeyStore?
KeyStore is a container for Keys. As simple as that.
Let’s know about the Keys and then, how it is stored in a KeyStore.
and
Let’s answer them, one by one.
Before digging in, if you are looking to create a self-signed certificate, then feel free to check this post,
What are those keys?
As the name suggests, keys are similar to our physical home keys with which we open/lock doors.
In a day to day world, we use different types of keys for home, car, garage, office, desk, safe, bank locker, and what not to keep our belongings and loved ones safe.
Similarly, a Key is a software token similar to our passwords with which we can lock/unlock our secret information.
If it is similar to a password, why can’t we just use password?
Passwords are created by humans and may contain characters from their spouse name, date of birth and might be easy to crack or guess.
On the other hand, a Key can help strength the password by implementing a cryptographic algorithm which is difficult to guess.
How do they look like?
They are in different forms similar to our physical keys like Private key, Public key, Key Pair, Secret key. And this is how their standard syntax looks like.
However, when it is transmitted or read it would be typically in an encoded standard format X.509 or PKCS#8.
How to create one?
Keys can be created thru command line keytool or using tool like KeyStore Explorer or even programmatically.
We need know at least the Key type and the Algorithm to get started with to create one.
Key type
These are the primary type of keys,
- Key Pair — Private Key, Public Key
- Secret Key
There are other different key types supported by external libraries like bounty castle.
Supported Algorithm
The following piece of code will list all the supported algorithms that can be used to generate a Key or a KeyPair
Once we know the type of Key. It is fairly straight forward to generate one. Here, is a simple Java code to generate a random Key.
The returned key can be used for ciphering secrets.
What would we do with it?
Technically we can do different things based on our needs. It narrows down to what the secret information is and how would we want to use or share the information.
An example of how it is used in a SSL certificate is detailed here,
It is also used in SSH, IoTs, Licenses, Email, Communication Protocols, etc.
How are the Keys stored in the KeyStore?
Being said about the key. Let’s see how they are stored. As mentioned earlier, KeyStore is the collection list of Keys as an Entry.
Similar to the Key we have similar tools to create a KeyStore. However, for this demonstration we will look into the programmatic way of creating one.
Finally, we have answered our questions.