KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jacorb > security > util > KeyStoreUtil


1 package org.jacorb.security.util;
2
3 /*
4  * JacORB - a free Java ORB
5  *
6  * Copyright (C) 2000-2004 Gerald Brose.
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the Free
20  * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21  */

22
23
24 import java.security.*;
25 import java.security.cert.*;
26 import java.io.*;
27 import javax.swing.*;
28 import javax.swing.event.*;
29 import javax.swing.table.*;
30 import javax.swing.tree.*;
31 import java.awt.*;
32 import java.awt.event.*;
33
34 import java.math.BigInteger JavaDoc;
35 import java.util.*;
36
37 import iaik.asn1.*;
38 import iaik.asn1.structures.*;
39 import iaik.x509.*;
40 import iaik.x509.extensions.*;
41
42 /**
43  * A class with utility methods that help managing a key store.
44  *
45  * @author Gerald Brose, FU Berlin
46  * @version $Id: KeyStoreUtil.java,v 1.10 2004/05/06 12:40:01 nicolas Exp $
47  */

48
49 public class KeyStoreUtil
50 {
51     /**
52      * @return - a fully loaded and operational KeyStore
53      * @param file_name - a keystore file name to be loaded
54      * @param storepass - the password for managing the keystore
55      */

56
57     public static KeyStore getKeyStore(String JavaDoc file_name, char[] storepass )
58     throws java.io.IOException JavaDoc, KeyStoreException, NoSuchAlgorithmException,
59     CertificateException
60     {
61         //try unchanged name first
62
File f = new File( file_name );
63         
64         if( ! f.exists() )
65         {
66             //try to prepend home dir
67
String JavaDoc name =
68                 System.getProperty( "user.home" ) +
69                 System.getProperty( "file.separator" ) +
70                 file_name;
71
72             f = new File( name );
73         }
74
75     FileInputStream in = new FileInputStream( f );
76
77     KeyStore ks;
78     // ks = KeyStore.getInstance("jks");
79

80     try
81     {
82         ks = KeyStore.getInstance( "IAIKKeyStore", "IAIK" );
83     }
84     catch ( java.security.NoSuchProviderException JavaDoc ex )
85     {
86         System.err.println ( ex.toString ());
87         ks = KeyStore.getInstance("jks");
88     }
89     ks.load(in, storepass);
90     in.close();
91     return ks;
92     }
93
94
95     /**
96      * @return - a key pair, if the alias refers to a valid key entry, null otherwise
97      * @param keystore - a keystore file name to be loaded
98      * @param alias - the alias for the key entry
99      * @param storepass - the password for managing the keystore
100      * @param password - the password used to protect the private key
101      */

102
103     public static java.security.KeyPair JavaDoc getKeyPair(String JavaDoc keystore,
104                            String JavaDoc alias,
105                            char[] storepass,
106                            char[] password)
107     throws java.io.IOException JavaDoc,
108     KeyStoreException, NoSuchAlgorithmException,
109     UnrecoverableKeyException, CertificateException
110     {
111     KeyStore ks = getKeyStore( keystore, storepass );
112
113     if(! ks.isKeyEntry(alias))
114        return null;
115
116     java.security.PrivateKey JavaDoc privateKey =
117         (java.security.PrivateKey JavaDoc)ks.getKey(alias,password);
118     java.security.cert.X509Certificate JavaDoc c =
119         (java.security.cert.X509Certificate JavaDoc)ks.getCertificate(alias);
120     java.security.PublicKey JavaDoc publicKey = c.getPublicKey();
121
122     return new java.security.KeyPair JavaDoc( publicKey, privateKey);
123     }
124
125     /**
126      * @return - a key pair, if the alias refers to a valid key entry, null otherwise
127      *
128      * @param ks - a keystore file name to be loaded
129      * @param alias - the alias for the key entry
130      * @param password - the password used to protect the private key
131      */

132
133     public static java.security.KeyPair JavaDoc getKeyPair(KeyStore ks,
134                            String JavaDoc alias,
135                            char[] password)
136     throws java.io.IOException JavaDoc,
137     KeyStoreException, NoSuchAlgorithmException,
138     UnrecoverableKeyException, CertificateException
139     {
140     if(! ks.isKeyEntry(alias))
141        return null;
142
143     java.security.PrivateKey JavaDoc privateKey =
144         (java.security.PrivateKey JavaDoc)ks.getKey(alias,password);
145     java.security.cert.X509Certificate JavaDoc c =
146         (java.security.cert.X509Certificate JavaDoc)ks.getCertificate(alias);
147
148     java.security.PublicKey JavaDoc publicKey = c.getPublicKey();
149     return new java.security.KeyPair JavaDoc( publicKey, privateKey);
150     }
151
152     /**
153      * @return - a key pair retrieved from a keystore, asking for user
154      * input with GUI support, null if user input is invalid or the key
155      * pair could not be found
156      */

157
158     public static java.security.KeyPair JavaDoc getKeyPair(KeyStore ks)
159     throws java.io.IOException JavaDoc,
160     KeyStoreException, NoSuchAlgorithmException,
161     UnrecoverableKeyException, CertificateException
162     {
163     String JavaDoc[] clear_input = new String JavaDoc[]{ "Entry Alias"};
164     char[][] opaque_input = new char[1][];
165
166     UserSponsor us = new UserSponsor("",
167                      "Please authenticate to retrieve key pair",
168                      clear_input,
169                      new String JavaDoc[]{ "Entry Password" }
170                      );
171
172     if( !us.getInput(clear_input, opaque_input))
173     {
174         System.err.println("Input cancelled");
175         System.exit(1);
176     }
177
178     String JavaDoc alias = clear_input[0];
179     char [] password = opaque_input[0];
180
181     if( alias == null || password == null )
182     {
183         return null;
184     }
185
186     return getKeyPair( ks, alias, password);
187     }
188
189
190     /**
191      * retrieve a key pair from a keystore, asking for user
192      * input with GUI support
193      */

194
195     public static java.security.KeyPair JavaDoc getKeyPair()
196     throws java.io.IOException JavaDoc,
197     KeyStoreException, NoSuchAlgorithmException,
198     UnrecoverableKeyException, CertificateException
199     {
200     String JavaDoc[] clear_input = new String JavaDoc[]{ "Keystore file", "Entry Alias"};
201     char[][] opaque_input = new char[2][];
202     
203     UserSponsor us = new UserSponsor("",
204                      "Please authenticate to retrieve key pair",
205                      clear_input,
206                      new String JavaDoc[]{ "Keystore Password", "Entry Password" });
207     
208     if( !us.getInput(clear_input, opaque_input))
209     {
210         System.err.println("Input cancelled");
211         System.exit(1);
212     }
213
214     String JavaDoc fname = clear_input[0];
215     String JavaDoc name = clear_input[1];
216     char [] ksPassword = opaque_input[0];
217     char [] entryPassword = opaque_input[1];
218
219     if( fname == null || name == null || ksPassword == null || entryPassword == null )
220     {
221         System.err.println("no input");
222         System.exit(1);
223     }
224
225     return getKeyPair( fname, name, ksPassword, entryPassword);
226     }
227
228     /**
229      * retrieve all Certficates from a key store file, prompt user for
230      * name and password if input is invalid
231      */

232
233     public static java.security.cert.X509Certificate JavaDoc [] getCerts(String JavaDoc fileName,
234                                  String JavaDoc name,
235                                  char[] password)
236     throws java.io.IOException JavaDoc,
237     KeyStoreException, NoSuchAlgorithmException,
238     UnrecoverableKeyException, CertificateException
239     {
240     if( name == null || name.length() == 0 || password == null )
241     {
242         return getCerts( fileName );
243     }
244
245     KeyStore ks = getKeyStore(fileName, password );
246     if(! ks.isKeyEntry(name))
247        return null;
248
249     return (java.security.cert.X509Certificate JavaDoc[])ks.getCertificateChain( name );
250
251     }
252
253
254     /**
255      * retrieve all Certficates from a key store file,prompt user for
256      * name and password
257      */

258
259     public static java.security.cert.X509Certificate JavaDoc [] getCerts(String JavaDoc fileName)
260     throws IOException, KeyStoreException, NoSuchAlgorithmException,
261     UnrecoverableKeyException, CertificateException
262     {
263     String JavaDoc[] clear_input = new String JavaDoc[]{ "User name"};
264     char[][] opaque_input = new char[1][];
265     
266     UserSponsor us = new UserSponsor("Authentication",
267                      "Please authenticate to retrieve certificates",
268                      clear_input,
269                      new String JavaDoc[]{ "Password"});
270     
271     if( !us.getInput(clear_input, opaque_input))
272     {
273         System.err.println("Input cancelled");
274         System.exit(1);
275     }
276
277     String JavaDoc name = clear_input[0];
278     char [] password = opaque_input[0];
279
280     if( name == null || password == null )
281     {
282         System.err.println("no input");
283         System.exit(1);
284     }
285
286     
287     KeyStore ks = getKeyStore(fileName, password );
288
289     if(! ks.isKeyEntry(name))
290         return null;
291
292     return (java.security.cert.X509Certificate JavaDoc[])ks.getCertificateChain( name );
293
294     }
295
296
297     /**
298      * retrieve all X509Certficates in a key store for a given alias that qualify
299      * a role certs, i.e. that have a V.3 extension of type SubjectAltName with
300      * a rfc 822 name component that starts with "role:"
301      */

302
303     public static java.security.cert.X509Certificate JavaDoc [] getRoleCerts(KeyStore ks,
304                                      String JavaDoc alias,
305                                      java.security.PublicKey JavaDoc[] trustees )
306     throws java.security.KeyStoreException JavaDoc,java.security.cert.CertificateEncodingException JavaDoc
307     {
308     if(! ks.isKeyEntry(alias))
309        return null;
310
311     Vector vector = new Vector();
312
313     java.security.cert.Certificate JavaDoc[] chain =
314         (java.security.cert.Certificate JavaDoc[])ks.getCertificateChain( alias );
315     for( int i = 0; i < chain.length; i++ )
316     {
317         try
318         {
319         iaik.x509.X509Certificate c = (iaik.x509.X509Certificate)chain[i];
320         if( !c.hasExtensions())
321             continue;
322
323         for( Enumeration extensions = c.listExtensions(); extensions.hasMoreElements();)
324         {
325             iaik.x509.V3Extension e = (iaik.x509.V3Extension)extensions.nextElement();
326             if( e instanceof SubjectAltName )
327             {
328             SubjectAltName san = (SubjectAltName)e;
329             GeneralNames gn = san.getGeneralNames();
330             for( Enumeration g = gn.getNames(); g.hasMoreElements(); )
331             {
332                 GeneralName generalName = (GeneralName)g.nextElement();
333                 if( generalName.getType() == GeneralName.rfc822Name )
334                 {
335                 String JavaDoc value = (String JavaDoc)generalName.getName();
336                 if( value.startsWith("role:"))
337                 {
338                     c.checkValidity();
339                     java.security.Signature JavaDoc sig =
340                     java.security.Signature.getInstance( c.getSigAlgName());
341
342                     for( int ii = 0; ii < trustees.length; ii++)
343                     {
344                     try
345                     {
346                         sig.initVerify( trustees[ii] );
347                         sig.verify( c.getSignature() );
348                         vector.addElement(c);
349                     }
350                     catch( SignatureException se )
351                     {
352                         continue;
353                     }
354                     catch( InvalidKeyException se )
355                     {
356                         continue;
357                     }
358                     }
359                 }
360                 }
361             }
362             }
363         }
364                 
365         }
366         catch(Exception JavaDoc e)
367         {
368         e.printStackTrace();
369         continue;
370         }
371     }
372
373     java.security.cert.X509Certificate JavaDoc[] result =
374         new java.security.cert.X509Certificate JavaDoc[vector.size()];
375     for( int i = 0; i < result.length; i++)
376     {
377         result[i] = (java.security.cert.X509Certificate JavaDoc)vector.elementAt(i);
378     }
379     return result;
380     }
381
382
383
384 }
385
386
387
388
389
390
391
392
393
394
395
396
397
Popular Tags