Sunday, February 12, 2012

Keystores

Keystores are used to store public/private keys and certificates, in a password protected manner.

Keystores are typically *.jks files, but there is no restriction on the filename or extension.

keytool is a Java utility used to create/manage keystores, keys and certificates.

To use keytool, make sure your JDK /bin directory is in your system PATH.

Now at a command prompt, type:

 C:\Users\mlavannis>keytool -genkey -alias org.confucius -keyalg RSA -keystore confucius.jks -keysize 2048  


This creates a new keystore ("confucius.jks") with a new set of RSA key-pair (aliased "org.confucius")

You will be asked a series of questions before the keystore and keys get created.

Use "changeit" as password for both the keystore and the key-pair.

Let us see how to access the key-pair from our Java code.

In your /src/org/confucius folder, create a class KeystoreAccess.java, like this:

 package org.confucius;  

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.Key;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;

public class KeystoreAccess {
private static final String keystorePassword = "changeit";
private static final String keyPassword = "changeit";
private static final String keystoreFile = "C:\\users\\mlavannis\\confucius.jks";
private static final String keyAlias = "org.confucius";

public static void main(String[] args){
try {
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(new FileInputStream(keystoreFile), keystorePassword.toCharArray());

Key key = keystore.getKey(keyAlias, keyPassword.toCharArray());
System.out.println("Key = " + key);

if (key instanceof PrivateKey) {
Certificate cert = keystore.getCertificate(keyAlias);
PublicKey publicKey = cert.getPublicKey();
System.out.println("Public Key = " + publicKey);
}
}
catch (KeyStoreException e) {
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

}



We load the keystore and the keys (using its alias), then access the private and public keys.

R-click on the file in Eclipse navigator and select Run As --> Java Application.

You will see the private and public keys printed in the console.

No comments: