Open In App

How to Import a .cer Certificate into a Java KeyStore?

Improve
Improve
Like Article
Like
Save
Share
Report

A Java KeyStore is a file that contains certificates. These certificates are used in the Java code. KeyStore and the certificates within it are used to make secure connections from the Java code. The certificates stored can be in several formats. A Java KeyStore is represented by the KeyStore(java.security.KeyStore) class. In this article, we are going to learn :

  • How to generate a java key store (JKS)
  • How to generate a certificate (CER)
  • How to import the certificate into our KeyStore

Pre-requisite: Make sure that we have keytool installed in our system.

Generating a Java Keystore (JKS)

To generate a JKS, we need to run the below command.

keytool -genkey -v -keystore <path\to\name-of-the-keystore.jks> -alias <ALIAS-NAME> -keyalg <PUBLIC-KEY-ALGORITHM> -keysize <SIZE> -validity <NUMBER-OF-DAYS>

For example:

keytool -genkey -v -keystore example.jks -alias GFG_ALIAS -keyalg RSA -keysize 2048 -validity 10000

When we hit enter, we need to answer a few questions. Refer to the snapshot below.

Output:

generating a jks

 

We can check the contents of this Keystore using the below command:

keytool -list -keystore <path\to\keystore-name.jks>

For example:

keytool -list -keystore example.jks

After we hit enter, we need to provide the password. We can see that there is only 1 entry with the alias we provided.

Output:

JKS Output

 

Generating a Certificate(CER)

There are many ways to generate a certificate. Here we will cover one of the most practical ways. When we visit a site and authenticate ourselves, we can copy the certificate to a file if we follow the below steps:

Click on the lock icon > connection is secure  > certificate is valid.

Generating a Certificate(CERT)

 

Go to Details tab > Copy to File > Next

 

In the next wizard, click next and choose a file location and file name. Then Click Finish. You will find a certificate in the path you selected.

Importing the certificate into our Keystore

Now that we have both the certificate and the Keystore, we can use the below command to import the .cer into our java Keystore.

keytool -import -trustcacerts -keystore <path\to\keystore-name.jks> -alias <ALIAS> -file <path\to\certificate.cer>

For example, 

keytool -import -trustcacerts -keystore example.jks -alias NEW-GFG-ALIAS -file example.cer

It will prompt for the password, where we have to give the Keystore password.

To verify, we can again run the list command:

keytool -list -keystore <path\to\keystore-name.jks>

For example:

keytool -list -keystore example.jks

Output:

Importing the certificate into our Keystore Output

 

We can see that our certificate has been imported successfully and there is an entry with the alias we provided.


Last Updated : 18 Aug, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads