KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ejbca > util > P12toPEM


1 /*************************************************************************
2  * *
3  * EJBCA: The OpenSource Certificate Authority *
4  * *
5  * This software is free software; you can redistribute it and/or *
6  * modify it under the terms of the GNU Lesser General Public *
7  * License as published by the Free Software Foundation; either *
8  * version 2.1 of the License, or any later version. *
9  * *
10  * See terms of license at gnu.org. *
11  * *
12  *************************************************************************/

13  
14 package org.ejbca.util;
15
16 import java.io.*;
17 import java.security.KeyStore JavaDoc;
18 import java.security.KeyStoreException JavaDoc;
19 import java.security.NoSuchAlgorithmException JavaDoc;
20 import java.security.NoSuchProviderException JavaDoc;
21 import java.security.PrivateKey JavaDoc;
22 import java.security.UnrecoverableKeyException JavaDoc;
23 import java.security.cert.*;
24 import java.util.Enumeration JavaDoc;
25
26 import org.apache.log4j.Logger;
27
28 /**
29  * P12toPEM is used to export PEM files from a single p12 file. The class exports the user
30  * certificate, user private key in seperated files and the chain of sub ca and ca certifikate in
31  * a third file. The PEM files will have the names <i>common name</i>.pem, <i>common
32  * name</i>Key.pem and <i>common name</i>CA.pem derived from the DN in user certificate.
33  *
34  * @version $Id: P12toPEM.java,v 1.1 2006/01/17 20:32:19 anatom Exp $
35  */

36 public class P12toPEM {
37     private static Logger log = Logger.getLogger(P12toPEM.class);
38     String JavaDoc exportpath = "./p12/pem/";
39     String JavaDoc p12File;
40     String JavaDoc password;
41     KeyStore JavaDoc ks = null;
42     
43     boolean overwrite = false;
44     byte[] beginCertificate = "-----BEGIN CERTIFICATE-----".getBytes();
45     byte[] endCertificate = "-----END CERTIFICATE-----".getBytes();
46     byte[] beginPrivateKey = "-----BEGIN PRIVATE KEY-----".getBytes();
47     byte[] endPrivateKey = "-----END PRIVATE KEY-----".getBytes();
48     byte[] NL = "\n".getBytes();
49
50     /**
51      * DOCUMENT ME!
52      *
53      * @param args DOCUMENT ME!
54      */

55     public static void main(String JavaDoc[] args) {
56         // Bouncy Castle security provider
57
CertTools.installBCProvider();
58
59         P12toPEM p12 = null;
60
61         try {
62             if (args.length > 2) {
63                 boolean overwrite = false;
64
65                 if (args[2].equalsIgnoreCase("true")) {
66                     overwrite = true;
67                 }
68
69                 p12 = new P12toPEM(args[0], args[1], overwrite);
70             } else if (args.length > 1) {
71                 p12 = new P12toPEM(args[0], args[1]);
72             } else {
73                 System.out.println(
74                     "Usage: P12toPEM <p12file> <p12password> [overwrite (true/false)(default false)]");
75                 System.exit(0);
76             }
77
78             p12.createPEM();
79         } catch (Exception JavaDoc e) {
80             e.printStackTrace();
81         }
82     }
83
84     /**
85      * Basic construtor for the P12toPEM class, set variables for the class.
86      *
87      * @param p12File p12File The (path +) name of the input p12 file.
88      * @param password password The password for the p12 file.
89      *
90      */

91     public P12toPEM(String JavaDoc p12File, String JavaDoc password) {
92         this.p12File = p12File;
93         this.password = password;
94     }
95
96     /**
97      * Basic construtor using a inmemory keystore instead for a file.
98      *
99      * @param ks the keystore to use.
100      * @param password password The password for the p12 file.
101      * @param overwrite overwrite If existing files should be overwritten.
102      */

103     public P12toPEM(KeyStore JavaDoc keystore, String JavaDoc password, boolean overwrite) {
104         this.password = password;
105         this.ks = keystore;
106         this.overwrite = overwrite;
107     }
108
109
110     /**
111      * Sets the directory where PEM-files wil be stores
112      *
113      * @param path path where PEM-files will be stores
114      */

115     public void setExportPath(String JavaDoc path) {
116         exportpath = path;
117     }
118
119     /**
120      * Constructor for the P12toPEM class.
121      *
122      * @param p12File p12File The (path +) name of the input p12 file.
123      * @param password password The password for the p12 file.
124      * @param overwrite overwrite If existing files should be overwritten.
125      */

126     public P12toPEM(String JavaDoc p12File, String JavaDoc password, boolean overwrite) {
127         this.p12File = p12File;
128         this.password = password;
129         this.overwrite = overwrite;
130     }
131
132     /**
133      * DOCUMENT ME!
134      *
135      * @throws KeyStoreException DOCUMENT ME!
136      * @throws FileNotFoundException DOCUMENT ME!
137      * @throws IOException DOCUMENT ME!
138      * @throws NoSuchProviderException DOCUMENT ME!
139      * @throws NoSuchAlgorithmException DOCUMENT ME!
140      * @throws CertificateEncodingException DOCUMENT ME!
141      * @throws CertificateException DOCUMENT ME!
142      * @throws UnrecoverableKeyException DOCUMENT ME!
143      */

144     public void createPEM()
145         throws KeyStoreException JavaDoc, FileNotFoundException, IOException, NoSuchProviderException JavaDoc,
146             NoSuchAlgorithmException JavaDoc, CertificateEncodingException, CertificateException,
147             UnrecoverableKeyException JavaDoc {
148          
149          if(this.ks == null){
150             ks = KeyStore.getInstance("PKCS12", "BC");
151             InputStream in = new FileInputStream(p12File);
152             ks.load(in, password.toCharArray());
153             in.close();
154         }
155         // Fid the key private key entry in the keystore
156
Enumeration JavaDoc e = ks.aliases();
157         Object JavaDoc o = null;
158         PrivateKey JavaDoc serverPrivKey = null;
159
160         while (e.hasMoreElements()) {
161             o = e.nextElement();
162
163             if (o instanceof String JavaDoc) {
164                 if ((ks.isKeyEntry((String JavaDoc) o)) &&
165                         ((serverPrivKey = (PrivateKey JavaDoc) ks.getKey((String JavaDoc) o, password.toCharArray())) != null)) {
166                     log.debug("Aliases " + o + " is KeyEntry.");
167
168                     break;
169                 }
170             }
171         }
172
173         log.debug((("Private key encode: " + serverPrivKey) == null) ? null
174                                                                      : serverPrivKey.getFormat());
175
176         byte[] privKeyEncoded = "".getBytes();
177
178         if (serverPrivKey != null) {
179             privKeyEncoded = serverPrivKey.getEncoded();
180         }
181
182         //Certificate chain[] = ks.getCertificateChain((String) o);
183
Certificate[] chain = KeyTools.getCertChain(ks, (String JavaDoc) o);
184         log.debug("Loaded certificate chain with length " + chain.length + " from keystore.");
185
186         X509Certificate userX509Certificate = (X509Certificate) chain[0];
187
188         byte[] output = userX509Certificate.getEncoded();
189         String JavaDoc sn = CertTools.getSubjectDN(userX509Certificate);
190         String JavaDoc userFile = CertTools.getPartFromDN(sn, "CN");
191         String JavaDoc filetype = ".pem";
192
193         File path = new File(exportpath);
194         path.mkdir();
195
196         File tmpFile = new File(path, userFile + filetype);
197
198         if (!overwrite) {
199             if (tmpFile.exists()) {
200                 log.error("File '" + tmpFile + "' already exists, don't overwrite.");
201
202                 return;
203             }
204         }
205
206         OutputStream out = new FileOutputStream(tmpFile);
207         out.write(beginCertificate);
208         out.write(NL);
209
210         byte[] userCertB64 = Base64.encode(output);
211         out.write(userCertB64);
212         out.write(NL);
213         out.write(endCertificate);
214         out.close();
215
216         tmpFile = new File(path, userFile + "-Key" + filetype);
217
218         if (!overwrite) {
219             if (tmpFile.exists()) {
220                 log.error("File '" + tmpFile + "' already exists, don't overwrite.");
221
222                 return;
223             }
224         }
225
226         out = new FileOutputStream(tmpFile);
227         out.write(beginPrivateKey);
228         out.write(NL);
229
230         byte[] privKey = Base64.encode(privKeyEncoded);
231         out.write(privKey);
232         out.write(NL);
233         out.write(endPrivateKey);
234         out.close();
235
236         tmpFile = new File(path, userFile + "-CA" + filetype);
237
238         if (!overwrite) {
239             if (tmpFile.exists()) {
240                 log.error("File '" + tmpFile + "' already exists, don't overwrite.");
241
242                 return;
243             }
244         }
245
246         if (CertTools.isSelfSigned(userX509Certificate)) {
247             log.info(
248                 "User certificate is selfsigned, this is a RootCA, no CA certificates written.");
249         } else {
250             out = new FileOutputStream(tmpFile);
251
252             for (int num = 1; num < chain.length; num++) {
253                 X509Certificate tmpX509Cert = (X509Certificate) chain[num];
254                 byte[] tmpOutput = tmpX509Cert.getEncoded();
255                 out.write(beginCertificate);
256                 out.write(NL);
257
258                 byte[] tmpCACertB64 = Base64.encode(tmpOutput);
259                 out.write(tmpCACertB64);
260                 out.write(NL);
261                 out.write(endCertificate);
262                 out.write(NL);
263             }
264
265             out.close();
266         }
267     }
268
269     // createPEM
270
}
271
272
273 // P12toPEM
274
Popular Tags