Import .cer in Java

Rupam Yadav Feb 15, 2024
Import .cer in Java

A .cer file is a certificate that helps identify and check any modification to the entity.

This article will learn how to import a certificate file with the .cer extension in a key store.

Import a .cer File Using the Keytool in Java

Keytool is a utility that comes with Java. We use it to manage the certificates and keystores.

It can be used to generate keystore and self-signed certificates too.

We get the following output that shows the additional commands when using the keytool command without any options.

That can be used for several operations like generating a certificate request, key-pair generation, printing the content of the certificate, etc.

Import .cer File in Java

The keytool command is importcert that imports a certificate. We also use the command -file to import a file, and then we specify the .cer file name, myCA.cer.

We need to specify the keystore where we want to import the certificate. We use -keystore with the Keystore name my-storekey2.keystore.

Then we tell the certificate’s alias that the keystore uses to identify the certificate.

keytool -importcert -file myCA.cer -keystore my-storekey2.keystore -alias "keystore1"

We get the following request to enter the Keystore password.

Enter Keystore password:

Once we enter the correct password and press the enter key, It will show information about the certificate, like the details of the owner and issuer and the validity of the certificate.

Output:

Owner: CN=John Doe, OU=Test, O=Test1, L=TestLocality, ST=TestState, C=IN
Issuer: CN=John Doe, OU=Test, O=Test1, L=TestLocality, ST=TestState, C=IN
Serial number: 352a75ae344aa1cd
Valid from: Mon Feb 07 12:20:25 IST 2022 until: Sun Nov 03 12:20:25 IST 2024
Certificate fingerprints:
         SHA1: AB:0A:C8:67:A9:31:09:FE:44:CC:6D:D2:2B:19:1A:F0:D6:A6:AB:1D
         SHA256: E1:1B:DD:2B:56:C8:C5:5B:24:7B:93:31:60:14:AC:8C:09:64:2B:73:8A:CB:44:37:19:FC:BE:35:EE:BA:F8:F1
Signature algorithm name: SHA256withRSA
Subject Public Key Algorithm: 2048-bit RSA key
Version: 3

Extensions:

#1: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: 4E 8C 16 C9 38 FA F4 D1   1B 45 E8 89 E1 B9 9E 90  N...8....E......
0010: 71 B3 D4 A4                                        q...
]
]

We can check if the certificate was imported in the keystore by listing all its certificates using the following command.

keytool -list -Keystore my-storekey.keystore

Output:

keystore1, 07-Feb-2022, PrivateKeyEntry,
Certificate fingerprint (SHA-256): E1:1B:DD:2B:56:C8:C5:5B:24:7B:93:31:60:14:AC:8C:09:64:2B:73:8A:CB:44:37:19:FC:BE:35:EE:BA:F8:F1

The output shows the certificate with its alias and fingerprint hash.

Author: Rupam Yadav
Rupam Yadav avatar Rupam Yadav avatar

Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.

LinkedIn