KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > security > KeyTool


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23 package com.sun.enterprise.security;
24
25 import java.security.Security JavaDoc;
26 import java.security.Provider JavaDoc;
27
28 import sun.security.tools.*;
29 import java.io.*;
30 import java.util.*;
31 import java.security.cert.*;
32 import java.security.KeyStore JavaDoc;
33 import java.security.Key JavaDoc;
34 import com.sun.enterprise.util.*;
35 import java.util.logging.*;
36 import com.sun.logging.*;
37
38 /**
39  * Wraps the J2SE's keytool after adding our provider.
40  * Provides the PKCS12 functionality - read a PKCS12 format
41  * keystore and replicate it into a "JKS" type keystore.
42  * @author Harish Prabandham
43  * @author Harpreet Singh
44  */

45 public final class KeyTool {
46
47     private static Logger _logger=null;
48     static {
49         _logger=LogDomains.getLogger(LogDomains.SECURITY_LOGGER);
50     }
51
52     private static final String JavaDoc JSSE_PROVIDER =
53         "com.sun.net.ssl.internal.ssl.Provider";
54
55     // The PKCS12 file to be replicated
56
private File inputFile=null;
57     // The JKS file output from the replication
58
private File outputFile=null;
59     private char[] jksKeyStorePass;
60     private char[] pkcsKeyStorePass = null;
61     // Password of the key
62
private char[] jksKeyPass = null;
63     private char[] pkcsKeyPass = null;
64
65     private String JavaDoc provider = null;
66     // The respective in-memory keystores
67
private KeyStore JavaDoc pkcs12KeyStore = null;
68     private KeyStore JavaDoc jksKeyStore = null;
69     
70     private static String JavaDoc PKCS12 = "-pkcs12";
71     private static String JavaDoc INFILE = "-pkcsFile";
72     private static String JavaDoc OUTFILE = "-jksFile";
73     private static String JavaDoc PKCSKEYSTOREPASS = "-pkcsKeyStorePass";
74     private static String JavaDoc PKCSKEYPASS = "-pkcsKeyPass";
75     // following 2 options not used currently - set to default
76
private static String JavaDoc JKSKEYSTOREPASS = "-jksKeyStorePass";
77     private static String JavaDoc JKSKEYPASS = "-jksKeyPass";
78     private static LocalStringManagerImpl localStrings =
79     new LocalStringManagerImpl(KeyTool.class);
80
81     /**
82      * The class is only instantiated for PKCS12 - all other
83      * keytool functionality is passed to the sun.security.tools.KeyTool
84      * @param the file name of the PKCS12 file
85      * @param the output file name of the JKS file
86      * @param the provider - In this case SunJSSE
87      * @param password to the PKCS12 keystore
88      * @param password to the key in the PKCS12 keystore
89      * @param password to the JKS keystore
90      * @param password to the key in the JKS keystore
91      * currently it has to be the same as the JKS keystore password
92      * @exception Problem in loading the keystores
93      */

94     public KeyTool (String JavaDoc infile, String JavaDoc outfile, String JavaDoc pkcsKeyStorePass,
95             String JavaDoc pkcsKeyPass, String JavaDoc jksKeyStorePass,
96             String JavaDoc jksKeyPass,
97             String JavaDoc provider) throws IOException {
98         inputFile = new File (infile);
99         outputFile = new File (outfile);
100         this.pkcsKeyStorePass = pkcsKeyStorePass.toCharArray ();
101         this.pkcsKeyPass = pkcsKeyPass.toCharArray ();
102         this.jksKeyStorePass = jksKeyStorePass.toCharArray ();
103         this.jksKeyPass = jksKeyPass.toCharArray ();
104         this.provider = provider;
105         // if the output file exists delete it and create a new file
106
try{
107         if (outputFile.exists ()){
108             throw new IOException ("Output file already exists!");
109         }
110         // Get the keystores from the engines.
111
pkcs12KeyStore = KeyStore.getInstance ("PKCS12", provider);
112         jksKeyStore = KeyStore.getInstance ("JKS");
113
114         } catch (Exception JavaDoc e) {
115         // catch possible security and io exceptions
116
throw new IOException (e.getMessage ());
117         }
118         readKeyStores ();
119     }
120     /**
121      * Load both the keystore's into memory.
122      * The PKCS12 is loaded from the file and the JKS file
123      * is created.
124      */

125     public void readKeyStores() throws IOException {
126     FileInputStream pkcsFis = null;
127     FileInputStream jksFis = null;
128     try {
129         pkcsFis = new FileInputStream(inputFile);
130         jksFis = new FileInputStream (outputFile);
131     } catch(Exception JavaDoc e) {
132
133     } finally {
134         try {
135         pkcs12KeyStore.load(pkcsFis, pkcsKeyStorePass);
136         // Dont need a password as creating a new
137
// keystore.
138
jksKeyStore.load (jksFis, null);
139         } catch(Exception JavaDoc ce) {
140         // Can't do much... too bad.
141
_logger.log(Level.SEVERE,
142                             "java_security.KeyStore_load_exception",ce);
143         }
144         if(pkcsFis != null)
145         pkcsFis.close();
146         if (jksFis != null)
147         jksFis.close ();
148         }
149     }
150     /**
151      * Write the JKS keystore that is populated with values from
152      * the PKCS12 keystore to the outputfile.
153      */

154     public void writeJksKeyStore() throws IOException {
155     FileOutputStream fos = null;
156     try {
157         fos = new FileOutputStream(outputFile);
158     } catch(Exception JavaDoc e) {
159         // No problem we'll create one....
160
// e.printStackTrace();
161
} finally {
162         try {
163         jksKeyStore.store (fos, jksKeyStorePass);
164         } catch(Exception JavaDoc ce) {
165         // Can't do much... too bad.
166
_logger.log(Level.SEVERE,
167                             "java_security.KeyStore_store_exception",ce);
168         }
169         if(fos != null)
170         fos.close();
171         }
172     }
173     /**
174      * Copies the keys and certificates in the PKCS12 file to
175      * the in-memory JKS keystore
176      * @exception If the keystore has not been instantiated or
177      * the password to the key is'nt proper
178      */

179     public void replicatePkcs12ToJks () throws Exception JavaDoc {
180     Enumeration e = pkcs12KeyStore.aliases ();
181     for (; e.hasMoreElements (); ){
182         String JavaDoc alias = (String JavaDoc)e.nextElement ();
183         if (pkcs12KeyStore.isKeyEntry (alias)){
184         
185         /* Get the key and associated certificate chain
186          * from PKCS12 keystore and put in JKS keystore
187          */

188         Key JavaDoc key = pkcs12KeyStore.getKey (alias, pkcsKeyPass);
189         Certificate[] certs =
190             pkcs12KeyStore.getCertificateChain (alias);
191         jksKeyStore.setKeyEntry (alias, key, jksKeyPass, certs);
192         } else if (pkcs12KeyStore.isCertificateEntry (alias)){
193
194         jksKeyStore.setCertificateEntry
195             (alias, pkcs12KeyStore.getCertificate (alias));
196         }
197     }
198     }
199     /**
200      * Prints the information in the PKCS12 keystore
201      */

202     public void info () throws Exception JavaDoc{
203         _logger.log(Level.FINEST," Keystore Information");
204         _logger.log(Level.FINEST," Type = " + pkcs12KeyStore.getType ());
205         _logger.log(Level.FINEST," Provider = "+ pkcs12KeyStore.getProvider ());
206         _logger.log(Level.FINEST," KeyStore size = "+pkcs12KeyStore.size ());
207     Enumeration e = pkcs12KeyStore.aliases ();
208         _logger.log(Level.FINEST," Kstore Aliases ");
209     for (; e.hasMoreElements (); ){
210         String JavaDoc alias = (String JavaDoc)e.nextElement ();
211             _logger.log(Level.FINEST," Alias = "+ alias);
212         if (pkcs12KeyStore.isKeyEntry (alias)){
213                 _logger.log(Level.FINEST,"Alias is a key entry ");
214         Key JavaDoc key = pkcs12KeyStore.getKey (alias, pkcsKeyPass);
215                 _logger.log(Level.FINEST," Format = "+key.getFormat ());
216         } else if (pkcs12KeyStore.isCertificateEntry (alias)){
217                 _logger.log(Level.FINEST," Alias is a certificate entry");
218         }
219     }
220         _logger.log(Level.FINEST," End of Information");
221     }
222     /**
223      * Initializes the provider to be the JSSE provider
224      */

225     public static void initProvider() {
226     try {
227         Provider JavaDoc p =
228         (Provider JavaDoc) Class.forName(JSSE_PROVIDER).newInstance();
229         Security.addProvider(p);
230
231     } catch(Exception JavaDoc e) {
232         _logger.log(Level.SEVERE,"java_security.provider_exception",e);
233     }
234     }
235     /**
236      * Gets the provider name for JSSE
237      */

238     public static String JavaDoc getProviderName (){
239     try{
240         Provider JavaDoc p =
241         (Provider JavaDoc) Class.forName(JSSE_PROVIDER).newInstance();
242         return p.getName ();
243     } catch (Exception JavaDoc e) {
244         _logger.log(Level.SEVERE,"java_security.getName_exception",e);
245     }
246     return null;
247     }
248     public static void help (boolean exit){
249
250     System.out.println
251         (localStrings.getLocalString ("enterprise.security.keytool",
252                       "keytool"));
253     System.out.println
254         (localStrings.getLocalString
255          ("enterprise.security.keytooloptions", "PKCS Options:"));
256     System.out.println (" "+ PKCS12 +
257                 " "+ INFILE + " fileName" +
258                 " "+ PKCSKEYSTOREPASS + " password" +
259                 " "+PKCSKEYPASS +" password" +
260                 " "+OUTFILE+ " outputFileName"+
261                 " "+JKSKEYSTOREPASS + " password");
262     /* uncomment when support for this present in JSSE
263        System.Out.Println (" "+JKSKEYPASS+ " password");
264     */

265     if (exit)
266         System.exit (-1);
267     }
268     public static void main(String JavaDoc[] args) {
269     boolean pkcs = false;
270     initProvider();
271     String JavaDoc provider = null;
272     String JavaDoc inFile = null;
273     String JavaDoc outFile = null;
274     String JavaDoc jksKeyPass = null;
275     String JavaDoc jksKeyStorePass = null;
276     String JavaDoc pkcsKeyPass = null;
277     String JavaDoc pkcsKeyStorePass = null;
278     try{
279         if (args.length == 0){
280         help (false);
281         sun.security.tools.KeyTool.main (args);
282         }
283         if (args[0].equalsIgnoreCase (PKCS12)){
284         pkcs = true;
285         if (args.length != 11)
286             help (true);
287         if (!args[1].equalsIgnoreCase (INFILE))
288             help (true);
289         inFile = args[2];
290         if (!args[3].equalsIgnoreCase (PKCSKEYSTOREPASS))
291             help (true);
292         pkcsKeyStorePass = args[4];
293         if (!args[5].equalsIgnoreCase (PKCSKEYPASS))
294             help (true);
295         pkcsKeyPass = args[6];
296         if (!args[7].equalsIgnoreCase (OUTFILE))
297             help (true);
298         outFile = args[8];
299         if (!args[9].equalsIgnoreCase (JKSKEYSTOREPASS))
300             help (true);
301         
302         jksKeyStorePass = args[10];
303         jksKeyPass = jksKeyStorePass;
304         /*
305         // Uncomment the following when support
306         // for different keystore and key pass present in JSSE
307
308         if (!args[11].equalsIgnoreCase (JKSKEYPASS))
309             help ();
310         jksKeyPass = args[12];
311         */

312         }
313         if (!pkcs){
314         sun.security.tools.KeyTool.main(args);
315         } else{
316         provider = getProviderName ();
317         KeyTool kt = new KeyTool (inFile, outFile, pkcsKeyStorePass,
318                       pkcsKeyPass, jksKeyStorePass,
319                       jksKeyPass,
320                       provider);
321         kt.replicatePkcs12ToJks ();
322         kt.writeJksKeyStore ();
323         }
324     } catch (Exception JavaDoc e){
325         _logger.log(Level.SEVERE,"java_security.main_exception",e);
326     }
327     }
328 }
329
330
331
332
Popular Tags