Friday 3 July 2015

Extract private, public key from keystore

In this post I am going to explain, how to extract public and private keys from keystore.

Step 1: generate jks file. Go through following post to generate jks file.

Step 2: Use following program to extract public and private keys form keystone.

import java.io.FileInputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;

public class ExtractKeyPair {

 public static KeyPair getKeyPair(String jksFile) throws Exception {
  FileInputStream is = new FileInputStream(jksFile);

  KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
  keystore.load(is, "password123".toCharArray());

  String alias = "certificate1";

  KeyPair pair = null;

  Key key = keystore.getKey(alias, "password123".toCharArray());
  if (key instanceof PrivateKey) {
   /* Get certificate of public key */
   Certificate cert = keystore.getCertificate(alias);

   /* Get public key */
   PublicKey publicKey = cert.getPublicKey();

   /* Construct KeyPair object */
   pair = new KeyPair(publicKey, (PrivateKey) key);

  }
  return pair;

 }

 public static void main(String[] argv) throws Exception {
  KeyPair keyPair = getKeyPair("/Users/harikrishna_gurram/keystore.jks");

  PrivateKey priKey = keyPair.getPrivate();
  PublicKey pubKey = keyPair.getPublic();

  byte data[] = priKey.getEncoded();
  for (byte b : data) {
   System.out.print(b);
  }

  System.out.println();
  data = pubKey.getEncoded();
  for (byte b : data) {
   System.out.print(b);
  }
 }
}

"/Users/harikrishna_gurram/keystore.jks" represents jks file, where certificate resides.

keystore.load(is, "password123".toCharArray());
Above statement loads keystore.

keystore.getKey(alias, "password123".toCharArray())
Above statement returns key associate with given certificate.



No comments:

Post a Comment