1 6 7 package org.mortbay.util; 8 9 import java.io.File ; 10 import java.io.FileInputStream ; 11 import java.io.FileOutputStream ; 12 import java.io.IOException ; 13 import java.io.InputStreamReader ; 14 import java.io.LineNumberReader ; 15 import java.io.OutputStream ; 16 import java.security.Key ; 17 import java.security.KeyStore ; 18 import java.security.cert.Certificate ; 19 import java.security.cert.X509Certificate ; 20 import java.util.Enumeration ; 21 22 50 public class PKCS12Import 51 { 52 public static void main(String [] args) throws Exception 53 { 54 if (args.length < 1) { 55 System.err.println( 56 "usage: java PKCS12Import {pkcs12file} [newjksfile]"); 57 System.exit(1); 58 } 59 60 File fileIn = new File (args[0]); 61 File fileOut; 62 if (args.length > 1) { 63 fileOut = new File (args[1]); 64 } else { 65 fileOut = new File ("newstore.jks"); 66 } 67 68 if (!fileIn.canRead()) { 69 System.err.println( 70 "Unable to access input keystore: " + fileIn.getPath()); 71 System.exit(2); 72 } 73 74 if (fileOut.exists() && !fileOut.canWrite()) { 75 System.err.println( 76 "Output file is not writable: " + fileOut.getPath()); 77 System.exit(2); 78 } 79 80 KeyStore kspkcs12 = KeyStore.getInstance("pkcs12"); 81 KeyStore ksjks = KeyStore.getInstance("jks"); 82 83 LineNumberReader in = new LineNumberReader (new InputStreamReader (System.in)); 84 System.out.print("Enter input keystore passphrase: "); 85 char[] inphrase = in.readLine().toCharArray(); 86 System.out.print("Enter output keystore passphrase: "); 87 char[] outphrase = in.readLine().toCharArray(); 88 89 kspkcs12.load(new FileInputStream (fileIn), inphrase); 90 91 ksjks.load( 92 (fileOut.exists()) 93 ? new FileInputStream (fileOut) : null, outphrase); 94 95 Enumeration eAliases = kspkcs12.aliases(); 96 int n = 0; 97 while (eAliases.hasMoreElements()) { 98 String strAlias = (String )eAliases.nextElement(); 99 System.err.println("Alias " + n++ + ": " + strAlias); 100 101 if (kspkcs12.isKeyEntry(strAlias)) { 102 System.err.println("Adding key for alias " + strAlias); 103 Key key = kspkcs12.getKey(strAlias, inphrase); 104 105 Certificate [] chain = kspkcs12.getCertificateChain(strAlias); 106 107 ksjks.setKeyEntry(strAlias, key, outphrase, chain); 108 } 109 } 110 111 OutputStream out = new FileOutputStream (fileOut); 112 ksjks.store(out, outphrase); 113 out.close(); 114 } 115 116 static void dumpChain(Certificate [] chain) 117 { 118 for (int i = 0; i < chain.length; i++) { 119 Certificate cert = chain[i]; 120 if (cert instanceof X509Certificate ) { 121 X509Certificate x509 = (X509Certificate )chain[i]; 122 System.err.println("subject: " + x509.getSubjectDN()); 123 System.err.println("issuer: " + x509.getIssuerDN()); 124 } 125 } 126 } 127 128 } 129 130 | Popular Tags |