Sunday, June 26, 2011

Save/Load public/private SSL keys!

Save/Load or.. Write/Read or.. Store/Retrieve Private Key/Public Key to/from disk/file.. !!

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import org.apache.log4j.Logger;

import com.mt.classification.InterfaceAudience;
import com.mt.classification.InterfaceStability;

/**
 * TODO Description go here.
 *
 * @author Varra
 * @version 1.0
 *
 */
@InterfaceAudience.Public
@InterfaceStability.Evolving
public class SSLKeyFinder
{
   
    /** The logger to log the debugging messages as application runs. */
    private static final Logger logger = Logger.getLogger(SSLKeyFinder.class);
   
    /**
     * The main method.
     *
     * @param args
     *            the arguments
     */
    public static void main(String args[])
    {
        final SSLKeyFinder keyFinder = new SSLKeyFinder();
        try
        {
            final String path = "C:\\Documents and Settings\\george\\My Documents\\workspaces\\gsoc09\\playground\\tmp";
            final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
            keyGen.initialize(1024);
            final KeyPair generatedKeyPair = keyGen.genKeyPair();
            logger.info("Generated Key Pair");
            keyFinder.dumpKeyPair(generatedKeyPair);
            keyFinder.SaveKeyPair(path, generatedKeyPair);
            final KeyPair loadedKeyPair = keyFinder.LoadKeyPair(path, "DSA");
            logger.info("Loaded Key Pair");
            keyFinder.dumpKeyPair(loadedKeyPair);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return;
        }
    }
   
    /**
     * Dump key pair.
     *
     * @param keyPair
     *            the key pair
     */
    private void dumpKeyPair(KeyPair keyPair)
    {
        final PublicKey pub = keyPair.getPublic();
        logger.info("Public Key: " + getHexString(pub.getEncoded()));
        final PrivateKey priv = keyPair.getPrivate();
        logger.info("Private Key: " + getHexString(priv.getEncoded()));
    }
   
    /**
     * Gets the hex string.
     *
     * @param b
     *            the b
     * @return the hex string
     */
    private String getHexString(byte[] b)
    {
        String result = "";
        for (int i = 0; i < b.length; i++)
        {
            result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
        }
        return result;
    }
   
    /**
     * Save key pair.
     *
     * @param path
     *            the path
     * @param keyPair
     *            the key pair
     * @throws IOException
     *             Signals that an I/O exception has occurred.
     */
    public void SaveKeyPair(String path, KeyPair keyPair) throws IOException
    {
        final PrivateKey privateKey = keyPair.getPrivate();
        final PublicKey publicKey = keyPair.getPublic();
        // Store Public Key.
        final X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded());
        FileOutputStream fos = new FileOutputStream(path + "/public.key");
        fos.write(x509EncodedKeySpec.getEncoded());
        fos.close();
        // Store Private Key.
        final PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
        fos = new FileOutputStream(path + "/private.key");
        fos.write(pkcs8EncodedKeySpec.getEncoded());
        fos.close();
    }
   
    /**
     * Loads the key pair.
     *
     * @param path
     *            the path
     * @param algorithm
     *            the algorithm
     * @return the key pair
     * @throws IOException
     *             Signals that an I/O exception has occurred.
     * @throws NoSuchAlgorithmException
     *             the no such algorithm exception
     * @throws InvalidKeySpecException
     *             the invalid key spec exception
     */
    public KeyPair LoadKeyPair(String path, String algorithm) throws IOException, NoSuchAlgorithmException,
            InvalidKeySpecException
    {
        // Read Public Key.
        final File filePublicKey = new File(path + "/public.key");
        FileInputStream fis = new FileInputStream(path + "/public.key");
        final byte[] encodedPublicKey = new byte[(int) filePublicKey.length()];
        fis.read(encodedPublicKey);
        fis.close();
        // Read Private Key.
        final File filePrivateKey = new File(path + "/private.key");
        fis = new FileInputStream(path + "/private.key");
        final byte[] encodedPrivateKey = new byte[(int) filePrivateKey.length()];
        fis.read(encodedPrivateKey);
        fis.close();
        // Generate KeyPair.
        final KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
        final X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey);
        final PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
        final PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
        final PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
       
        return new KeyPair(publicKey, privateKey);
    }
}

No comments:

Post a Comment