KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sourceforge > jcetaglib > lib > CertTools


1 package net.sourceforge.jcetaglib.lib;
2
3 import net.sourceforge.jcetaglib.tools.Hex;
4 import net.sourceforge.jcetaglib.tools.KeyTools;
5 import org.bouncycastle.asn1.ASN1Sequence;
6 import org.bouncycastle.asn1.DERInputStream;
7 import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier;
8 import org.bouncycastle.asn1.x509.SubjectKeyIdentifier;
9 import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
10 import org.bouncycastle.util.encoders.Base64;
11
12 import java.io.*;
13 import java.security.*;
14 import java.security.cert.*;
15 import java.security.spec.InvalidKeySpecException JavaDoc;
16 import java.security.spec.PKCS8EncodedKeySpec JavaDoc;
17 import java.util.StringTokenizer JavaDoc;
18
19 /**
20  * Tools to handle common certificate operations.
21  *
22  * @version $Id: CertTools.java,v 1.4 2004/04/15 07:28:25 hamgert Exp $
23  */

24 public class CertTools {
25
26     //private static Category cat = Category.getInstance(CertTools.class.getName());
27

28     /** Creates new CertTools */
29     public CertTools() {
30     }
31
32
33     /**
34      * Gets a specified part of a DN.
35      *
36      * @param dn String containing DN, The DN string has the format "C=SE, O=xx, OU=yy, CN=zz".
37      * @param dnpart String specifying which part of the DN to get, should be "CN" or "OU" etc.
38      * @return String containing dnpart or null if dnpart is not present
39      */

40     public static String JavaDoc getPartFromDN(String JavaDoc dn, String JavaDoc dnpart) {
41         String JavaDoc trimmeddn = dn.trim();
42         String JavaDoc part = null, o = null;
43         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(trimmeddn, ",=");
44         while (st.hasMoreTokens()) {
45             o = st.nextToken();
46             if (o.trim().equalsIgnoreCase(dnpart)) {
47                 part = st.nextToken();
48             }
49         }
50         return part;
51     } //getCNFromDN
52

53     public static PrivateKey getPrivatefromPEM(String JavaDoc keyFile, String JavaDoc keypwd)
54             throws IOException, NoSuchAlgorithmException, InvalidKeySpecException JavaDoc, Exception JavaDoc {
55         InputStream inStrm = new FileInputStream(keyFile);
56         PrivateKey privKey = getPrivatefromPEM(inStrm, keypwd);
57         return privKey;
58     }
59
60     public static PrivateKey getPrivatefromPEM(InputStream keystream, String JavaDoc keypwd)
61             throws IOException, NoSuchAlgorithmException, InvalidKeySpecException JavaDoc, Exception JavaDoc {
62
63         String JavaDoc beginKey;
64         String JavaDoc endKey;
65
66         if (keypwd == null || keypwd == "") {
67             beginKey = "-----BEGIN PRIVATE KEY-----";
68             endKey = "-----END PRIVATE KEY-----";
69         } else {
70             beginKey = "-----BEGIN ENCRYPTED PRIVATE KEY-----";
71             endKey = "-----END ENCRYPTED PRIVATE KEY-----";
72         }
73
74         BufferedReader bufRdr = new BufferedReader(new InputStreamReader(keystream));
75         ByteArrayOutputStream ostr = new ByteArrayOutputStream();
76         PrintStream opstr = new PrintStream(ostr);
77         String JavaDoc temp;
78         while ((temp = bufRdr.readLine()) != null &&
79                 !temp.equals(beginKey))
80             continue;
81         if (temp == null)
82             throw new IOException("Error in " + keystream.toString() + ", missing " + beginKey + " boundary");
83         while ((temp = bufRdr.readLine()) != null &&
84                 !temp.equals(endKey))
85             opstr.print(temp);
86         if (temp == null)
87             throw new IOException("Error in " + keystream.toString() + ", missing " + endKey + " boundary");
88
89         opstr.close();
90
91         byte[] keybuf = Base64.decode(ostr.toByteArray());
92
93         PrivateKey privKey = null;
94
95         // get the private key - private keys are encoded in PKCS#8 format:
96
PKCS8EncodedKeySpec JavaDoc prvSpec = new PKCS8EncodedKeySpec JavaDoc(keybuf);
97
98         if (keypwd == null || keypwd == "") {
99             KeyFactory kf = KeyFactory.getInstance("RSA");
100             privKey = kf.generatePrivate(prvSpec);
101         } else {
102             privKey = KeyTools.decryptPrivateKey(keybuf, keypwd);
103         }
104
105         return privKey;
106     }
107
108
109     /**
110      * Reads a certificate in PEM-format from a file. The file may contain other things,
111      * the first certificate in the file is read.
112      *
113      * @param certFile the file containing the certificate in PEM-format
114      * @return X509Certificate
115      * @exception IOException if the filen cannot be read.
116      * @exception CertificateException if the filen does not contain a correct certificate.
117      */

118     public static X509Certificate getCertfromPEM(String JavaDoc certFile) throws IOException, CertificateException {
119         InputStream inStrm = new FileInputStream(certFile);
120         X509Certificate cert = getCertfromPEM(inStrm);
121         return cert;
122     }
123
124     /**
125      * Reads a certificate in PEM-format from an InputStream. The stream may contain other things,
126      * the first certificate in the stream is read.
127      *
128      * @param certstream the input stream containing the certificate in PEM-format
129      * @return X509Certificate
130      * @exception IOException if the stream cannot be read.
131      * @exception CertificateException if the stream does not contain a correct certificate.
132      */

133     public static X509Certificate getCertfromPEM(InputStream certstream)
134             throws IOException, CertificateException {
135
136         String JavaDoc beginKey = "-----BEGIN CERTIFICATE-----";
137         String JavaDoc endKey = "-----END CERTIFICATE-----";
138         BufferedReader bufRdr = new BufferedReader(new InputStreamReader(certstream));
139         ByteArrayOutputStream ostr = new ByteArrayOutputStream();
140         PrintStream opstr = new PrintStream(ostr);
141         String JavaDoc temp;
142         while ((temp = bufRdr.readLine()) != null &&
143                 !temp.equals(beginKey))
144             continue;
145         if (temp == null)
146             throw new IOException("Error in " + certstream.toString() + ", missing " + beginKey + " boundary");
147         while ((temp = bufRdr.readLine()) != null &&
148                 !temp.equals(endKey))
149             opstr.print(temp);
150         if (temp == null)
151             throw new IOException("Error in " + certstream.toString() + ", missing " + endKey + " boundary");
152         opstr.close();
153
154         byte[] certbuf = Base64.decode(ostr.toByteArray());
155
156         // Phweeew, were done, now decode the cert from file back to X509Certificate object
157
CertificateFactory cf = CertificateFactory.getInstance("X.509");
158         X509Certificate x509cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certbuf));
159
160         return x509cert;
161     } // getCertfromPEM
162

163     /**
164      * Creates X509CRL from byte[].
165      *
166      * @param crl byte array containing CRL in DER-format
167      * @return X509CRL
168      * @exception CertificateException if the byte arrayen does not contani a correct CRL.
169      * @exception CRLException if the byte arrayen does not contani a correct CRL.
170      */

171     public static X509CRL getCRLfromByteArray(byte[] crl)
172             throws CertificateException, CRLException {
173         CertificateFactory cf = CertificateFactory.getInstance("X.509");
174         X509CRL x509crl = (X509CRL) cf.generateCRL(new ByteArrayInputStream(crl));
175         return x509crl;
176     } // getCRLfromByteArray
177

178     /**
179      * Checks if a certificate is self signed by verifying if subject and issuer are the same.
180      *
181      * @param cert the certificate that skall be checked.
182      * @return boolean true if the certificate has the same issuer and subject, false otherwise.
183      */

184     public static boolean isSelfSigned(X509Certificate cert) {
185         boolean ret = cert.getSubjectDN().equals(cert.getIssuerDN());
186         return ret;
187     } // isSelfSigned
188

189     //
190
// create the authority key identifier.
191
//
192
public static SubjectKeyIdentifier createSubjectKeyId(PublicKey pubKey) {
193         try {
194             ByteArrayInputStream bIn = new ByteArrayInputStream(pubKey.getEncoded());
195             SubjectPublicKeyInfo info = new SubjectPublicKeyInfo((ASN1Sequence) new DERInputStream(bIn).readObject());
196
197             return new SubjectKeyIdentifier(info);
198         } catch (Exception JavaDoc e) {
199             throw new RuntimeException JavaDoc("error creating key");
200         }
201     }
202
203     public static AuthorityKeyIdentifier createAuthorityKeyId(PublicKey pubKey) {
204         try {
205             ByteArrayInputStream bIn = new ByteArrayInputStream(pubKey.getEncoded());
206             SubjectPublicKeyInfo info = new SubjectPublicKeyInfo((ASN1Sequence) new DERInputStream(bIn).readObject());
207
208             return new AuthorityKeyIdentifier(info);
209         } catch (Exception JavaDoc e) {
210             throw new RuntimeException JavaDoc("error creating AuthorityKeyId");
211         }
212     }
213
214
215     /**
216      * Generate SHA1 fingerprint of certificate in string representation.
217      *
218      * @param cert X509Certificate.
219      * @return String containing hex format of SHA1 fingerprint.
220      **/

221     public static String JavaDoc getFingerprintAsString(X509Certificate cert) {
222
223         try {
224             byte[] res = generateSHA1Fingerprint(cert.getEncoded());
225             return Hex.encode(res);
226         } catch (CertificateEncodingException cee) {
227             System.out.println("Error encoding X509 certificate." + cee);
228         }
229         return null;
230     }
231
232     /**
233      * Generate a SHA1 fingerprint from a byte array containing a X.509 certificate
234      *
235      * @param ba Byte array containing DER encoded X509Certificate.
236      * @return Byte array containing SHA1 hash of DER encoded certificate.
237      */

238     public static byte[] generateSHA1Fingerprint(byte[] ba) {
239         try {
240             MessageDigest md = MessageDigest.getInstance("SHA1");
241             return md.digest(ba);
242         } catch (NoSuchAlgorithmException nsae) {
243             System.out.println("SHA1 algorithm not supported" + nsae);
244         }
245         return null;
246     } // generateSHA1Fingerprint
247

248 } // CertTools
249

250
Popular Tags