KickJava   Java API By Example, From Geeks To Geeks.

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


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 import java.security.*;
24 import java.security.cert.*;
25 import java.io.*;
26 import javax.swing.*;
27 import javax.swing.event.*;
28 import javax.swing.table.*;
29 import javax.swing.tree.*;
30 import java.awt.*;
31 import java.awt.event.*;
32
33 import java.math.BigInteger JavaDoc;
34 import java.util.*;
35
36 import iaik.asn1.*;
37 import iaik.asn1.structures.*;
38 import iaik.x509.*;
39 import iaik.x509.extensions.*;
40
41 /**
42  * A class with utility methods that help managing certificates
43  *
44  * @author Gerald Brose, FU Berlin
45  * @version $Id: CertUtils.java,v 1.11 2004/05/06 12:40:01 nicolas Exp $
46  */

47
48 public class CertUtils
49 {
50     /**
51      * @return - a self signed X509v3 public key certificate
52      *
53      * @param subjectKey - the public key to be signed
54      * @param privKey - the signature key
55      * The signature algorithm will be selected accoring to
56      * the type of the private key, i.e. dsaWithSHA1 for DSA keys
57      * and md5WithRSAEncryption for RSA keys
58      */

59     
60     public static iaik.x509.X509Certificate createPublicKeyCert(iaik.asn1.structures.Name subject,
61                                 iaik.asn1.structures.Name issuer,
62                                 java.security.PublicKey JavaDoc subjectKey,
63                                 java.security.PrivateKey JavaDoc privKey)
64     throws iaik.x509.X509ExtensionException, java.security.cert.CertificateException JavaDoc,
65     java.security.NoSuchAlgorithmException JavaDoc, java.security.InvalidKeyException JavaDoc
66     {
67     iaik.x509.X509Certificate cert = new iaik.x509.X509Certificate();
68     
69     if( subject == null )
70         subject = emptyName();
71     if( issuer == null )
72         issuer = emptyName();
73     
74     cert.setIssuerDN( issuer );
75     cert.setSubjectDN( subject );
76     cert.setPublicKey( subjectKey );
77     
78     java.util.Date JavaDoc now = new java.util.Date JavaDoc();
79     
80     cert.setSerialNumber( new BigInteger JavaDoc( Long.toString( now.getTime() )));
81     cert.setValidNotBefore( now );
82     
83     java.util.Calendar JavaDoc cal = java.util.Calendar.getInstance();
84     cal.add(java.util.Calendar.MONTH, 12);
85     cert.setValidNotAfter(cal.getTime());
86
87     if( privKey instanceof java.security.interfaces.DSAPrivateKey JavaDoc )
88         cert.sign(iaik.asn1.structures.AlgorithmID.dsaWithSHA1,
89               privKey);
90     else if ( privKey instanceof java.security.interfaces.RSAPrivateKey JavaDoc )
91         cert.sign(iaik.asn1.structures.AlgorithmID.md5WithRSAEncryption,
92               privKey);
93     else
94         throw new java.security.InvalidKeyException JavaDoc("Unknown private key: " +
95                                                         privKey.getClass().getName());
96
97     return cert;
98     }
99
100
101     /**
102      * @return - an X509v3 certificate with an SubjectAltName extension that
103      * represents a role name. The format of the extension is an ASN.1 string
104      * "role:<rolename>".
105      */

106
107     public static iaik.x509.X509Certificate certifyRoleMembership(
108                           String JavaDoc rolename,
109                           iaik.asn1.structures.Name subject,
110                           iaik.asn1.structures.Name issuer,
111                           java.security.PublicKey JavaDoc subjectKey,
112                           java.security.PrivateKey JavaDoc privKey)
113     throws iaik.x509.X509ExtensionException, java.security.cert.CertificateException JavaDoc,
114     java.security.NoSuchAlgorithmException JavaDoc, java.security.InvalidKeyException JavaDoc
115     {
116
117         iaik.x509.X509Certificate cert = new iaik.x509.X509Certificate();
118     
119         if( subject == null )
120         subject = emptyName();
121         if( issuer == null )
122         issuer = emptyName();
123
124         cert.setIssuerDN( issuer );
125         cert.setSubjectDN( subject );
126         cert.setPublicKey( subjectKey );
127
128         java.util.Date JavaDoc now = new java.util.Date JavaDoc();
129
130         cert.setSerialNumber( new BigInteger JavaDoc( Long.toString( now.getTime() )));
131         cert.setValidNotBefore( now );
132
133         java.util.Calendar JavaDoc cal = java.util.Calendar.getInstance();
134         cal.add(java.util.Calendar.MONTH, 12);
135         cert.setValidNotAfter(cal.getTime());
136
137         /* add an extension */
138
139         GeneralName gn = new GeneralName( GeneralName.rfc822Name,"role:" + rolename );
140         GeneralNames generalNames = new GeneralNames(gn );
141
142         iaik.x509.extensions.SubjectAltName ext = new SubjectAltName( generalNames );
143         cert.addExtension(ext);
144
145         if( privKey instanceof java.security.interfaces.DSAPrivateKey JavaDoc )
146         cert.sign(iaik.asn1.structures.AlgorithmID.dsaWithSHA1,
147               (java.security.PrivateKey JavaDoc)privKey);
148         else if ( privKey instanceof java.security.interfaces.RSAPrivateKey JavaDoc )
149         cert.sign(iaik.asn1.structures.AlgorithmID.md5WithRSAEncryption,
150               (java.security.PrivateKey JavaDoc)privKey);
151
152         System.out.println("Cert signed");
153         return cert;
154     }
155
156     public static iaik.asn1.structures.Name emptyName()
157     {
158     iaik.asn1.structures.Name subject = new iaik.asn1.structures.Name();
159     subject.addRDN(ObjectID.commonName, "");
160     subject.addRDN(ObjectID.organizationalUnit, "");
161     subject.addRDN(ObjectID.organization, "");
162     subject.addRDN(ObjectID.locality, "");
163     subject.addRDN(ObjectID.country, "");
164     return subject;
165     }
166
167     public static iaik.asn1.structures.Name createName(String JavaDoc alias)
168     {
169     iaik.asn1.structures.Name subject = new iaik.asn1.structures.Name();
170     subject.addRDN(ObjectID.commonName, alias);
171     subject.addRDN(ObjectID.organizationalUnit, "AGSS");
172     subject.addRDN(ObjectID.organization, "FU Berlin");
173     subject.addRDN(ObjectID.locality, "Berlin");
174     subject.addRDN(ObjectID.country, "DE");
175     return subject;
176     }
177
178     public static String JavaDoc getCertLabel(java.security.cert.X509Certificate JavaDoc cert)
179     throws iaik.x509.X509ExtensionException, java.security.cert.CertificateException JavaDoc,
180     java.security.NoSuchAlgorithmException JavaDoc, java.security.InvalidKeyException JavaDoc
181     {
182     String JavaDoc label = getRoleName(cert);
183     if( label == null )
184     {
185         label = cert.getSubjectDN() + ", signer: " + cert.getIssuerDN();
186     }
187     return label;
188     }
189
190     public static String JavaDoc getRoleName(java.security.cert.X509Certificate JavaDoc cert)
191     throws iaik.x509.X509ExtensionException, java.security.cert.CertificateException JavaDoc,
192     java.security.NoSuchAlgorithmException JavaDoc, java.security.InvalidKeyException JavaDoc
193     {
194         iaik.x509.X509Certificate c;
195         
196         try
197         {
198             c = (iaik.x509.X509Certificate)cert;
199         }
200         catch( ClassCastException JavaDoc ccce )
201         {
202             c = new iaik.x509.X509Certificate( cert.getEncoded());
203         }
204         
205         if( !c.hasExtensions())
206             return null;
207         
208         c.checkValidity();
209         
210         for( Enumeration extensions = c.listExtensions(); extensions.hasMoreElements();)
211         {
212             iaik.x509.V3Extension e = (iaik.x509.V3Extension)extensions.nextElement();
213             if( e instanceof SubjectAltName )
214             {
215                 SubjectAltName san = (SubjectAltName)e;
216                 GeneralNames gn = san.getGeneralNames();
217                 for( Enumeration g = gn.getNames(); g.hasMoreElements(); )
218                 {
219                     GeneralName generalName = (GeneralName)g.nextElement();
220                     if( generalName.getType() == GeneralName.rfc822Name )
221                     {
222                         String JavaDoc value = (String JavaDoc)generalName.getName();
223                         if( value.startsWith("role:"))
224                             return value.substring(5);;
225                     }
226                 }
227             }
228         }
229         // nothing found
230
return null;
231 // }
232
// catch( Exception e)
233
// {
234
// e.printStackTrace();
235
// return null;
236
// }
237
}
238
239     public static boolean isRoleCert(java.security.cert.X509Certificate JavaDoc cert)
240     throws iaik.x509.X509ExtensionException, java.security.cert.CertificateException JavaDoc,
241     java.security.NoSuchAlgorithmException JavaDoc, java.security.InvalidKeyException JavaDoc
242     {
243     try
244     {
245         iaik.x509.X509Certificate c;
246
247         try
248         {
249         c = (iaik.x509.X509Certificate)cert;
250         }
251         catch( ClassCastException JavaDoc ccce )
252         {
253         c = new iaik.x509.X509Certificate( cert.getEncoded());
254         }
255
256         if( !c.hasExtensions())
257         return false;
258
259         for( Enumeration extensions = c.listExtensions(); extensions.hasMoreElements();)
260         {
261         iaik.x509.V3Extension e = (iaik.x509.V3Extension)extensions.nextElement();
262         if( e instanceof SubjectAltName )
263         {
264             SubjectAltName san = (SubjectAltName)e;
265             GeneralNames gn = san.getGeneralNames();
266             for( Enumeration g = gn.getNames(); g.hasMoreElements(); )
267             {
268             GeneralName generalName = (GeneralName)g.nextElement();
269             if( generalName.getType() == GeneralName.rfc822Name )
270             {
271                 String JavaDoc value = (String JavaDoc)generalName.getName();
272                 if( value.startsWith("role:"))
273                 return true;
274             }
275             }
276         }
277         }
278         // nothing found
279
return false;
280
281     }
282     catch( Exception JavaDoc e)
283     {
284         e.printStackTrace();
285         return false;
286     }
287     }
288
289     /*
290      * Verifies a certificate chain.
291      *
292      * The certificate of the user is the first one in the list
293      * and the top level certificate is the last one.
294      * chain[0] = user certificate signed issuer1
295      * chain[1] = issuer1 certificate signed issuer2
296      * ...
297      * chain[n] = self signed CA certificate
298      *
299      * @author Andre Benvenuti, GST Bern
300      * @return - true if we can verify all the certificates in the chain
301      * and if CA is a trusted signer.
302      *
303      * @param chain the certificate chain to verify
304      * @param keyStore - the keyStore to search for trusted signers
305      */

306
307     public static boolean verifyCertificateChain ( java.security.cert.X509Certificate JavaDoc[] chain,
308                            java.security.KeyStore JavaDoc keyStore
309                          )
310     throws iaik.x509.X509ExtensionException, java.security.cert.CertificateException JavaDoc,
311     java.security.NoSuchAlgorithmException JavaDoc, java.security.InvalidKeyException JavaDoc,
312         java.security.NoSuchProviderException JavaDoc, java.security.KeyStoreException JavaDoc,
313         java.security.SignatureException JavaDoc
314     {
315     int len = chain.length;
316         chain[ len - 1 ].verify( chain [ len - 1 ].getPublicKey ());
317
318         for ( int i = len - 1; i > 0; i-- )
319         {
320             chain[ i - 1 ].verify( chain[ i ].getPublicKey ());
321         }
322         
323         // this won't work: the name is not an alias.
324
String JavaDoc alias = chain[ len - 1 ].getIssuerDN ().getName();
325         int index = alias.indexOf ( "CN=" ) + 3;
326         int l = alias.length ();
327         alias = alias.substring ( index, l );
328         return keyStore.isCertificateEntry( alias );
329     }
330     
331     public static java.security.cert.X509Certificate JavaDoc readCertificate(String JavaDoc fileName)
332     throws iaik.x509.X509ExtensionException, java.security.cert.CertificateException JavaDoc,
333     java.security.NoSuchAlgorithmException JavaDoc, java.security.InvalidKeyException JavaDoc,
334         java.security.NoSuchProviderException JavaDoc, java.io.IOException JavaDoc
335     {
336         java.security.cert.CertificateFactory JavaDoc factory =
337             java.security.cert.CertificateFactory.getInstance("X.509", "IAIK") ;
338         return (java.security.cert.X509Certificate JavaDoc)factory.generateCertificate(
339             new FileInputStream( fileName ));
340     }
341
342
343 }
344
345
346
347
Popular Tags