Tuesday, December 29, 2015

Use Java Security to export/import key pair into/from memory blob

I provide the example program of Java Security to explain how to

  1. export RSA key pair into memory blob.
  2. import RSA key pair from memory blob.
This example helps us to handle certificate or public key, that are generated by OpenSSL tool, in Java environment.

// generate an RSA-2048 key
System.out.println( "\nGenerate RSA-2048 key pair." );
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);
KeyPair key = keyGen.generateKeyPair();

// Export key pair into memory blob.
System.out.println( "Export key pair into memory blob." );
PublicKey pub = key.getPublic ();
PrivateKey prv = key.getPrivate ();
byte[] pubBlob = pub.getEncoded();
byte[] prvBlob = prv.getEncoded();
System.out.println ("Public key with " + pubBlob.length + " bytes: " + pubBlob);
System.out.println ("Private key with " + prvBlob.length + " bytes: " + prvBlob);

// Import key pair from memory blob.
System.out.println( "Import key pair from memory blob." );
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pub2 = keyFactory.generatePublic (
                    new X509EncodedKeySpec(pubBlob));
PrivateKey prv2 = keyFactory.generatePrivate(
                    new PKCS8EncodedKeySpec(prvBlob));
KeyPair key2 = new KeyPair (pub2, prv2);

// Check if the two key pairs are same.
if (pub.equals (pub2) && prv.equals (prv2)) {
    System.out.println ("Both key pairs are same");
} else {
    System.out.println ("Both key pairs are different");
}

-Count    

1 comment: