KickJava   Java API By Example, From Geeks To Geeks.

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


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.File JavaDoc;
17 import java.io.FileInputStream JavaDoc;
18 import java.io.FileNotFoundException JavaDoc;
19 import java.io.FileOutputStream JavaDoc;
20 import java.io.IOException JavaDoc;
21 import java.io.InputStream JavaDoc;
22 import java.io.OutputStream JavaDoc;
23 import java.security.KeyStore JavaDoc;
24 import java.security.KeyStoreException JavaDoc;
25 import java.security.NoSuchAlgorithmException JavaDoc;
26 import java.security.PrivateKey JavaDoc;
27 import java.security.UnrecoverableKeyException JavaDoc;
28 import java.security.cert.Certificate JavaDoc;
29 import java.security.cert.CertificateEncodingException JavaDoc;
30 import java.security.cert.CertificateException JavaDoc;
31 import java.security.cert.X509Certificate JavaDoc;
32 import java.util.Enumeration JavaDoc;
33
34
35 /**
36  * JKStoPEM is used to export PEM files from a single jks file. The class exports the user
37  * certificate, user private key in seperated files and the chain of sub ca and ca certifikate in
38  * a third file. The PEM files will have the names <i>common name</i>.pem, <i>common
39  * name</i>Key.pem and <i>common name</i>CA.pem derived from the DN in user certificate.
40  *
41  * @version $Id: JKStoPEM.java,v 1.1 2006/01/17 20:32:19 anatom Exp $
42  */

43 public class JKStoPEM {
44     String JavaDoc exportpath = "./p12/pem/";
45     String JavaDoc jksFile;
46     String JavaDoc password;
47     String JavaDoc keypass;
48     KeyStore JavaDoc ks = null;
49
50     boolean overwrite = false;
51     byte[] beginCertificate = "-----BEGIN CERTIFICATE-----".getBytes();
52     byte[] endCertificate = "-----END CERTIFICATE-----".getBytes();
53     byte[] beginPrivateKey = "-----BEGIN PRIVATE KEY-----".getBytes();
54     byte[] endPrivateKey = "-----END PRIVATE KEY-----".getBytes();
55     byte[] NL = "\n".getBytes();
56
57     /**
58      * DOCUMENT ME!
59      *
60      * @param args DOCUMENT ME!
61      */

62     public static void main(String JavaDoc[] args) {
63
64         // Bouncy Castle security provider
65
CertTools.installBCProvider();
66
67         JKStoPEM jks = null;
68
69         try {
70             if (args.length > 4) {
71                 boolean overwrite = false;
72
73                 if (args[4].equalsIgnoreCase("true")) {
74                     overwrite = true;
75                 }
76
77                 jks = new JKStoPEM(args[0], args[1], args[2], args[3], overwrite);
78             } else if (args.length > 3) {
79                 jks = new JKStoPEM(args[0], args[1], args[2], args[3]);
80             } else {
81                 System.out.println(
82                     "Usage: JKStoPEM <jksFile> <jkspassword> <keypassword> <outpath> [overwrite (true/false)(default false)]");
83                 System.exit(0);
84             }
85
86             jks.createPEM();
87         } catch (Exception JavaDoc e) {
88             e.printStackTrace();
89         }
90     }
91
92     /**
93      * Basic construtor for the JKStoPEM class, set variables for the class.
94      *
95      * @param jksFile jksFile The (path +) name of the input jks file.
96      * @param password password The password for the jks file.
97      *
98      */

99     public JKStoPEM(String JavaDoc jksFile, String JavaDoc password, String JavaDoc keypass, String JavaDoc outpath) {
100         this.jksFile = jksFile;
101         this.password = password;
102         this.keypass = keypass;
103         exportpath = outpath;
104     }
105
106     /**
107      * Basic construtor using a inmemory keystore instead for a file.
108      *
109      * @param ks the keystore to use.
110      * @param password password The password for the jks file.
111      * @param overwrite overwrite If existing files should be overwritten.
112      */

113     public JKStoPEM(KeyStore JavaDoc keystore, String JavaDoc password, String JavaDoc keypass, String JavaDoc outpath, boolean overwrite) {
114         this.password = password;
115         this.ks = keystore;
116         this.keypass = keypass;
117         exportpath = outpath;
118         this.overwrite = overwrite;
119     }
120
121
122     /**
123      * Sets the directory where PEM-files wil be stores
124      *
125      * @param path path where PEM-files will be stores
126      */

127     public void setExportPath(String JavaDoc path) {
128         exportpath = path;
129     }
130
131     /**
132      * Constructor for the JKStoPEM class.
133      *
134      * @param jksFile jksFile The (path +) name of the input jks file.
135      * @param password password The password for the jks file.
136      * @param overwrite overwrite If existing files should be overwritten.
137      */

138     public JKStoPEM(String JavaDoc jksFile, String JavaDoc password, String JavaDoc keypass, String JavaDoc outpath, boolean overwrite) {
139         this.jksFile = jksFile;
140         this.password = password;
141         this.overwrite = overwrite;
142         this.keypass = keypass;
143         exportpath = outpath;
144    }
145
146     /**
147      * DOCUMENT ME!
148      *
149      * @throws KeyStoreException DOCUMENT ME!
150      * @throws FileNotFoundException DOCUMENT ME!
151      * @throws IOException DOCUMENT ME!
152      * @throws NoSuchProviderException DOCUMENT ME!
153      * @throws NoSuchAlgorithmException DOCUMENT ME!
154      * @throws CertificateEncodingException DOCUMENT ME!
155      * @throws CertificateException DOCUMENT ME!
156      * @throws UnrecoverableKeyException DOCUMENT ME!
157      */

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

277 } // JKStoPEM
278
Popular Tags