Prog how-to

general programming

Faces context not found. getResponseWriter will fail »

Move a Private Key
Between Two JKS Keystore Files

The current article shows you how to move a private key between two JKS keystore files.

General
JKS keystores are binary files holding one or more keys in Java. The keys are used for SSL connectivity. There are two key types, private and public. The private key holds the site identity. The public key is generated from the private key and it is passed to the other party where it is installed in a special JKS keystore.

Most of the time, the keystore files are manipulated with a special Java tool called keytool. The tool can be found in the bin folder of the Java installation.

In order to move a key from a keystore file to the other, you need to export the key from the original keystore and import it in the second one.

Problem
When you use keytool with the export option on a private key, the tool does not extract the actual private key from the store (for security reasons). Only the public key is extracted.

That means you can’t use keytool for this operation.

Solution
There is a class in JDK called java.security.KeyStore. Keytool is implemented using this class functionality as well.

Given a JKS keystore file, we will write the code that will proceed through the following steps:

  1. Open the keystore file
  2. Load both the key and the keychain
  3. Open another keystore
  4. Save the loaded key in the keystore

First we assume we have two keystores, one is called first.jks and contains a private key under the alias first, and one called second.jks empty.

The full page code is here

And here is the result while listing the second keystore:

C:\temp\certs>keytool -list -storepass second -keystore second.jks

Keystore type: jks
Keystore provider: SUN

Your keystore contains 1 entry

second, 10-Oct-2008, keyEntry,
Certificate fingerprint (MD5): 33:8A:A3:7C:9E:FD:31:39:17:A1:E4:F4:0D:3B:C1:8F

Tags:

2 Responses to “Move a Private Key
Between Two JKS Keystore Files”

  1. Eduardo says:

    Sorry, but your information is not accurate.

    keytool -importkeystore -srckeystore keystore1.jks -destkeystore keystore2.jks

  2. Daniel says:

    Hi, Eduardo,

    Indeed, this solution is currently available. The solution I mentioned is for earlier jdks where this option was not available. At jdk 1.4 it was not available.

Leave a Reply