Java KeyStore create key store file

Description

Java KeyStore create key store file

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Collection;
import java.util.Iterator;

public class Main {
   public static void main(String args[]) throws Exception {
      char[] password = "123456".toCharArray();
      String alias = "aKey", name = "aStore.jks";
      KeyStore ks = KeyStore.getInstance("JKS", "SUN");
      ks.load(null, password);/* www  .  ja  va 2s  . com*/

      FileInputStream fis = new FileInputStream(args[0]);
      byte[] kdata = new byte[fis.available()];
      fis.read(kdata);

      PKCS8EncodedKeySpec kp = new PKCS8EncodedKeySpec(kdata);
      KeyFactory kf = KeyFactory.getInstance("DSA");
      PrivateKey pri = kf.generatePrivate(kp);

      CertificateFactory cf = CertificateFactory.getInstance("X.509");

      Collection c = cf.generateCertificates(new FileInputStream(args[1]));
      Certificate[] certs = new Certificate[c.size()];

      int in = 0;
      for (Iterator i = c.iterator(); i.hasNext();)
         certs[in++] = (Certificate) i.next();
      ks.setKeyEntry(alias, pri, password, certs);
      ks.store(new FileOutputStream(name), password);
      System.out.println("Key and certificate stored.");
   }
}



PreviousNext

Related