Wednesday, September 7, 2011

Accessing Security Certificates

package org.best.example;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.util.Enumeration;

public class AccessingCertificates {

  public static void main( String[] args ) throws Exception {
    final String keyStore = "acme";
    final String keyStorePass = "danger";
    final String keyPass = "password";

    // load information into a keystore
    java.security.KeyStore ks = java.security.KeyStore.getInstance( "JKS" );
    java.io.FileInputStream ksfis = new java.io.FileInputStream( keyStore );
    java.io.BufferedInputStream ksbufin = new java.io.BufferedInputStream( ksfis );
    ks.load( ksbufin, keyStorePass.toCharArray() );

    // list aliases in the keystore
    java.io.FileOutputStream fos = null;
    for( java.util.Enumeration theAliases = ks.aliases(); theAliases.hasMoreElements(); ) {
      String alias = (String) theAliases.nextElement();
      java.security.cert.Certificate cert = ks.getCertificate( alias );
      ByteUtils.saveBytesToFile( alias + ".cer", cert.getEncoded() );
      ByteUtils.saveBytesToFile( alias + ".pubkey", cert.getPublicKey().getEncoded() );
      java.security.PrivateKey privateKey = (java.security.PrivateKey) ks.getKey( alias, keyPass.toCharArray() );
      ByteUtils.saveBytesToFile( alias + ".privKey", privateKey.getEncoded() );
      System.out.println( "### generated certificate information for -> " + alias );
      System.out.println( cert );
    }
  }
}

No comments: