Generating, storing and retrieving Private Keys

Some applications does not work with certificates to perform security operations. Instead of this, raw private keys are used for signature or ciphering. Hence, private keys must be stored as PCKS#8 rather than PCKS#12.  

The following code shows how to generate and use a DSA private key of 1024 bits. Note that this key is stored using Base64 encoding in order to achieve appropiate results. And also Base64 code it’s not provided, any available code would work.

import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.spec.DSAPrivateKeySpec;
import java.security.spec.PKCS8EncodedKeySpec;

import sun.security.provider.DSAPrivateKey;

public class PrivateKeyOps {

  /**
   * Generate a DSA private key 1024 bits
   * @return DSA private key 1024 bits
   * @throws Exception
   */
  @SuppressWarnings( "unchecked" )
  private static PrivateKey generate() throws Exception {

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
    kpg.initialize(1024, new SecureRandom());
    KeyPair kp = kpg.generateKeyPair();

    Class spec = Class.forName("java.security.spec.DSAPrivateKeySpec");
    KeyFactory kf = KeyFactory.getInstance("DSA");
    DSAPrivateKeySpec dsaPrivKeySpec =
      (DSAPrivateKeySpec)kf.getKeySpec(kp.getPrivate(), spec);

    return new DSAPrivateKey(
        dsaPrivKeySpec.getX(),
                dsaPrivKeySpec.getP(),
                dsaPrivKeySpec.getQ(),
                dsaPrivKeySpec.getG());

  }

  /**
   * Store a PKCS8 base64 encoded private key in a file
   * @param fileName
   * @param generatedPK
   * @throws Exception
   */
  private static void store(String fileName, byte[] generatedPK) throws Exception {
        BufferedWriter keybw = new BufferedWriter(new FileWriter(fileName));
        keybw.write(Base64.encode(generatedPK));
        keybw.close();
  }

  /**
   * Retrieve a PKCS8 base64 encoded private key from a file
   * @param fileName
   * @return
   * @throws Exception
   */
  private static byte[] retrieve(String fileName) throws Exception {
        FileInputStream keyfis = new FileInputStream(fileName);
        byte[] loadedEncKey = new byte[keyfis.available()];
        keyfis.read(loadedEncKey);
        keyfis.close();
        return Base64.decode(new String(loadedEncKey));
  }

  /**
   * Load a PrivateKey object from an encoded key
   * @param encKey Encoded key
   * @return PrivateKey object
   * @throws Exception
   */
  private static PrivateKey load(byte[] encKey) throws Exception {
        PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(encKey);
        KeyFactory keyFactory = KeyFactory.getInstance("DSA");
        return keyFactory.generatePrivate(privKeySpec);
  }

  /**
   * Generate a private key
   * Store it on a file using base64 encoding
   * Retrieve it from the file using base64 decoding
   * Load the private key
   * @param args No args required
   * @throws Exception
   */
  public static void main(String...args) throws Exception {

    // Generate and store DSA Private Key
    byte[] generatedPK = generate().getEncoded();
    store("key.pem", generatedPK);

        // Retrieve and load DSA Private Key
    byte[] retrievedEncKey = retrieve("key.pem");
    byte[] loadedPK = load(retrievedEncKey).getEncoded();

    // See how it looks
    System.out.println(Base64.encode(loadedPK));

  }

}

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s