KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2   Name: X509Cert.java
3   Licensing: LGPL
4
5   API: Sun (http://java.sun.com) JCE 1.2.2 API (cleanroom implementation by Bouncy Castle)
6   Provider: Bouncy Castle (http://www.bouncycastle.org)
7
8   Disclaimer:
9
10   COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY OF ANY KIND,
11   EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE
12   IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE ENTIRE
13   RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED CODE IS WITH YOU. SHOULD ANY COVERED CODE
14   PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR)
15   ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY
16   CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED
17   HEREUNDER EXCEPT UNDER THIS DISCLAIMER.
18
19   (C) Copyright 2003 Gert Van Ham
20 */

21
22 package net.sourceforge.jcetaglib.lib;
23
24 import net.sourceforge.jcetaglib.exceptions.CryptoException;
25 import net.sourceforge.jcetaglib.tools.FileTools;
26 import net.sourceforge.jcetaglib.tools.KeyTools;
27 import org.bouncycastle.asn1.*;
28 import org.bouncycastle.asn1.misc.MiscObjectIdentifiers;
29 import org.bouncycastle.asn1.misc.NetscapeCertType;
30 import org.bouncycastle.asn1.x509.*;
31 import org.bouncycastle.jce.PKCS10CertificationRequest;
32 import org.bouncycastle.jce.X509Principal;
33 import org.bouncycastle.jce.X509V2CRLGenerator;
34 import org.bouncycastle.jce.X509V3CertificateGenerator;
35 import org.bouncycastle.jce.netscape.NetscapeCertRequest;
36 import org.bouncycastle.jce.provider.BouncyCastleProvider;
37 import org.bouncycastle.util.encoders.Base64;
38
39 import java.io.ByteArrayInputStream JavaDoc;
40 import java.io.FileInputStream JavaDoc;
41 import java.io.FileOutputStream JavaDoc;
42 import java.io.IOException JavaDoc;
43 import java.math.BigInteger JavaDoc;
44 import java.security.*;
45 import java.security.cert.Certificate JavaDoc;
46 import java.security.cert.*;
47 import java.util.Date JavaDoc;
48
49
50 /**
51  * Create/Read/Manipulate X.509 certificates
52  *
53  * @author Gert Van Ham
54  * @author hamgert@users.sourceforge.net
55  * @author http://jcetaglib.sourceforge.net
56  * @version $Id: X509Cert.java,v 1.3 2004/04/15 07:28:25 hamgert Exp $
57  */

58 public class X509Cert {
59
60     private static final String JavaDoc NS_CA = "ca";
61     private static final String JavaDoc NS_SERVER = "server";
62     private static final String JavaDoc NS_CLIENT = "client";
63     private static final String JavaDoc NS_ALL = "all";
64
65     /**
66      * Generate key pair (public & private key)
67      *
68      * @param keypairalgorithm keypair algorithm (e.g. "RSA")
69      * @param keylength key length (e.g. 1024)
70      * @param seed seed for SecureRandom (optional)
71      * @return generated keypair
72      * @throws NoSuchAlgorithmException unknown algorithm
73      * @throws NoSuchProviderException unknown provider
74      * @throws CryptoException cryptographic errors
75      */

76     public static KeyPair generateKeyPair(String JavaDoc keypairalgorithm
77                                           , int keylength
78                                           , byte[] seed) throws NoSuchAlgorithmException, NoSuchProviderException, CryptoException {
79
80         Security.addProvider(new BouncyCastleProvider());
81
82         KeyPairGenerator g = KeyPairGenerator.getInstance(keypairalgorithm, "BC");
83
84         SecureRandom sr = Seed.getSecureRandom(seed);
85
86         g.initialize(keylength, sr);
87         return g.generateKeyPair();
88     }
89
90     /**
91      * Creates a self-signed certificate
92      *
93      * @param privatekey the private key
94      * @param publickey the public key
95      * @param signaturealgorithm signature algorithm (e.g. "MD5WithRSAEncryption")
96      * @param validity defines how long this certificate is valid (in days)
97      * @param subjectdn the subject's distinguised name
98      * @param isca true if this certificate can be used for a Certificate Authority, false if not
99      * @param netscapeextensions adds netscape certificate extensions ("ca", "server", "client", "all")
100      * @return X.509 certificate
101      * @throws CertificateException certificate errors
102      */

103     public static X509Certificate selfsign(PrivateKey privatekey
104                                            , PublicKey publickey
105                                            , String JavaDoc signaturealgorithm
106                                            , long validity
107                                            , String JavaDoc subjectdn
108                                            , boolean isca
109                                            , String JavaDoc netscapeextensions) throws CertificateException {
110         try {
111             // Add Bouncy Castle provider
112
Security.addProvider(new BouncyCastleProvider());
113
114             Date JavaDoc firstDate = new Date JavaDoc();
115             // Set back startdate ten minutes to avoid some problems with wrongly set clocks.
116
firstDate.setTime(firstDate.getTime() - 10 * 60 * 1000);
117             Date JavaDoc lastDate = new Date JavaDoc();
118             // validity in days = validity*24*60*60*1000 milliseconds
119
lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000)));
120
121             X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();
122
123             // Serialnumber is random bits, where random generator is initialized with Date.getTime()
124
byte[] serno = new byte[8];
125             SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
126             random.setSeed((new Date JavaDoc().getTime()));
127             random.nextBytes(serno);
128
129             BigInteger JavaDoc sn = new java.math.BigInteger JavaDoc(serno).abs();
130
131             // Add certificate basic elements
132
v3CertGen.setSerialNumber(sn);
133             v3CertGen.setIssuerDN(new X509Principal(subjectdn));
134             v3CertGen.setNotBefore(firstDate);
135             v3CertGen.setNotAfter(lastDate);
136             v3CertGen.setSubjectDN(new X509Principal(subjectdn));
137             v3CertGen.setPublicKey(publickey);
138             v3CertGen.setSignatureAlgorithm(signaturealgorithm);
139
140             // Add certificate extensions
141
v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier,
142                     false,
143                     CertTools.createSubjectKeyId(publickey));
144
145             v3CertGen.addExtension(X509Extensions.BasicConstraints,
146                     false,
147                     new BasicConstraints(isca));
148
149             // Add Netscape extensions
150
if (NS_CA.equalsIgnoreCase(netscapeextensions)) {
151                 v3CertGen.addExtension(MiscObjectIdentifiers.netscapeCertType,
152                         false,
153                         new NetscapeCertType(NetscapeCertType.sslCA | NetscapeCertType.smimeCA | NetscapeCertType.objectSigningCA));
154             } else if (NS_SERVER.equalsIgnoreCase(netscapeextensions)) {
155                 v3CertGen.addExtension(MiscObjectIdentifiers.netscapeCertType,
156                         false,
157                         new NetscapeCertType(NetscapeCertType.sslServer));
158             } else if (NS_CLIENT.equalsIgnoreCase(netscapeextensions)) {
159                 v3CertGen.addExtension(MiscObjectIdentifiers.netscapeCertType,
160                         false,
161                         new NetscapeCertType(NetscapeCertType.sslClient | NetscapeCertType.smime | NetscapeCertType.objectSigning));
162             } else if (NS_ALL.equalsIgnoreCase(netscapeextensions)) {
163                 v3CertGen.addExtension(MiscObjectIdentifiers.netscapeCertType,
164                         false,
165                         new NetscapeCertType(NetscapeCertType.sslClient | NetscapeCertType.sslServer | NetscapeCertType.smime | NetscapeCertType.objectSigning | NetscapeCertType.sslCA | NetscapeCertType.smimeCA | NetscapeCertType.objectSigningCA));
166             }
167
168             // generate the certificate
169
X509Certificate cert = v3CertGen.generateX509Certificate(privatekey);
170
171             // check if certificate is valid
172
cert.checkValidity(new Date JavaDoc());
173             // verify certificate with public key
174
cert.verify(publickey);
175
176             return cert;
177         } catch (Exception JavaDoc e) {
178             e.printStackTrace();
179             throw new CertificateException(e.getMessage());
180         }
181     }
182
183     /**
184      * Create a signed certificate
185      *
186      * @param publickey the public key
187      * @param issuerprivatekey the private key of the CA (issuer)
188      * @param issuercertificate the certificate of the CA (issuer)
189      * @param signaturealgorithm signature algorithm (e.g. "MD5WithRSAEncryption")
190      * @param validity defines how long this certificate is valid (in days)
191      * @param subjectdn the subject's distinguised name
192      * @param isca true if this certificate can be used for a Certificate Authority, false if not
193      * @param crldisturi the CRL distribution URI
194      * @param netscapeextensions adds netscape certificate extensions ("ca", "server", "client", "all")
195      * @return X.509 certificate
196      * @throws CertificateException
197      */

198     public static X509Certificate sign(PublicKey publickey
199                                        , PrivateKey issuerprivatekey
200                                        , X509Certificate issuercertificate
201                                        , String JavaDoc signaturealgorithm
202                                        , long validity
203                                        , String JavaDoc subjectdn
204                                        , boolean isca
205                                        , String JavaDoc crldisturi
206                                        , String JavaDoc netscapeextensions) throws CertificateException {
207         try {
208             // Add Bouncy Castle provider
209
Security.addProvider(new BouncyCastleProvider());
210
211             Date JavaDoc firstDate = new Date JavaDoc();
212             // Set back startdate ten minutes to avoid some problems with wrongly set clocks.
213
firstDate.setTime(firstDate.getTime() - 10 * 60 * 1000);
214             Date JavaDoc lastDate = new Date JavaDoc();
215             // validity in days = validity*24*60*60*1000 milliseconds
216
lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000)));
217
218             X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();
219
220             // Serialnumber is random bits, where random generator is initialized with Date.getTime()
221
byte[] serno = new byte[8];
222             SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
223             random.setSeed((new Date JavaDoc().getTime()));
224             random.nextBytes(serno);
225
226             BigInteger JavaDoc sn = new java.math.BigInteger JavaDoc(serno).abs();
227             String JavaDoc issuerDN = issuercertificate.getSubjectDN().toString();
228
229             // Add certificate basic elements
230
v3CertGen.setSerialNumber(sn);
231             v3CertGen.setIssuerDN(new X509Principal(issuerDN));
232             v3CertGen.setNotBefore(firstDate);
233             v3CertGen.setNotAfter(lastDate);
234             v3CertGen.setSubjectDN(new X509Principal(subjectdn));
235             v3CertGen.setPublicKey(publickey);
236             v3CertGen.setSignatureAlgorithm(signaturealgorithm);
237
238             // Add certificate extensions
239
v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier,
240                     false,
241                     CertTools.createSubjectKeyId(publickey));
242
243             v3CertGen.addExtension(X509Extensions.AuthorityKeyIdentifier,
244                     false,
245                     CertTools.createAuthorityKeyId(issuercertificate.getPublicKey()));
246
247             v3CertGen.addExtension(X509Extensions.BasicConstraints,
248                     false,
249                     new BasicConstraints(isca));
250
251             // Add CRL distribution URI
252
if (crldisturi != null && !crldisturi.equalsIgnoreCase("")) {
253                 GeneralName gn = new GeneralName(new DERIA5String(crldisturi), 6);
254                 DERSequence seq = new DERSequence(gn);
255                 GeneralNames gns = new GeneralNames(seq);
256                 DistributionPointName dpn = new DistributionPointName(0, gns);
257                 DistributionPoint distp = new DistributionPoint(dpn, null, null);
258                 v3CertGen.addExtension(X509Extensions.CRLDistributionPoints.getId(), false, distp);
259             }
260
261             // Add Netscape extensions
262
if (NS_CA.equalsIgnoreCase(netscapeextensions)) {
263                 v3CertGen.addExtension(MiscObjectIdentifiers.netscapeCertType,
264                         false,
265                         new NetscapeCertType(NetscapeCertType.sslCA | NetscapeCertType.smimeCA | NetscapeCertType.objectSigningCA));
266             } else if (NS_SERVER.equalsIgnoreCase(netscapeextensions)) {
267                 v3CertGen.addExtension(MiscObjectIdentifiers.netscapeCertType,
268                         false,
269                         new NetscapeCertType(NetscapeCertType.sslServer));
270             } else if (NS_CLIENT.equalsIgnoreCase(netscapeextensions)) {
271                 v3CertGen.addExtension(MiscObjectIdentifiers.netscapeCertType,
272                         false,
273                         new NetscapeCertType(NetscapeCertType.sslClient | NetscapeCertType.smime | NetscapeCertType.objectSigning));
274             } else if (NS_ALL.equalsIgnoreCase(netscapeextensions)) {
275                 v3CertGen.addExtension(MiscObjectIdentifiers.netscapeCertType,
276                         false,
277                         new NetscapeCertType(NetscapeCertType.sslClient | NetscapeCertType.sslServer | NetscapeCertType.smime | NetscapeCertType.objectSigning | NetscapeCertType.sslCA | NetscapeCertType.smimeCA | NetscapeCertType.objectSigningCA));
278             }
279
280             // generate the certificate
281
X509Certificate cert = v3CertGen.generateX509Certificate(issuerprivatekey);
282
283             // check if certificate is valid
284
cert.checkValidity(new Date JavaDoc());
285             // verify certificate with public key
286
cert.verify(issuercertificate.getPublicKey());
287
288             return cert;
289         } catch (Exception JavaDoc e) {
290             e.printStackTrace();
291             throw new CertificateException(e.getMessage());
292         }
293     }
294
295     /**
296      * Create a CRL (Certification Revokation List)
297      *
298      * @param certserialnumbers array of certificate serial numbers that are revoked
299      * @param crlnumber the CRL number
300      * @param crlperiod how long this CRL is valid (in hours)
301      * @param signaturealgorithm signature algorithm (e.g. "MD5WithRSAEncryption")
302      * @param cacert the CA's certificate
303      * @param caprivkey the CA's private key (to sign the CRL)
304      * @return CRL
305      * @throws CertificateException
306      */

307     public static X509CRL CreateCRL(BigInteger JavaDoc[] certserialnumbers
308                                     , int crlnumber
309                                     , long crlperiod
310                                     , String JavaDoc signaturealgorithm
311                                     , X509Certificate cacert
312                                     , PrivateKey caprivkey) throws CertificateException {
313         X509CRL crl = null;
314         try {
315             // Add Bouncy Castle provider
316
Security.addProvider(new BouncyCastleProvider());
317
318             Date JavaDoc thisUpdate = new Date JavaDoc();
319             Date JavaDoc nextUpdate = new Date JavaDoc();
320             // crlperiod is hours = crlperiod*60*60*1000 milliseconds
321
nextUpdate.setTime(nextUpdate.getTime() + (crlperiod * 60 * 60 * 1000));
322
323             X509V2CRLGenerator crlgen = new X509V2CRLGenerator();
324             crlgen.setThisUpdate(thisUpdate);
325             crlgen.setNextUpdate(nextUpdate);
326             crlgen.setSignatureAlgorithm(signaturealgorithm);
327
328             // The CA issues & signs the CRL
329
crlgen.setIssuerDN(new X509Principal(cacert.getSubjectDN().toString()));
330
331             for (int i = 0; i < certserialnumbers.length; i++) {
332                 crlgen.addCRLEntry(certserialnumbers[i], thisUpdate, 0);
333             }
334
335             crlgen.addExtension(X509Extensions.AuthorityKeyIdentifier,
336                     false,
337                     CertTools.createAuthorityKeyId(cacert.getPublicKey()));
338
339             CRLNumber crlnum = new CRLNumber(BigInteger.valueOf(crlnumber));
340             crlgen.addExtension(X509Extensions.CRLNumber.getId(), false, crlnum);
341
342             crl = crlgen.generateX509CRL(caprivkey);
343
344             return crl;
345         } catch (Exception JavaDoc e) {
346             e.printStackTrace();
347             throw new CertificateException(e.getMessage());
348         }
349     }
350
351     /**
352      * Verify a certificate
353      *
354      * @param cert certificate to verify
355      * @param cacert CA's certificate
356      * @param crl CRL
357      * @return status (INVALID, REVOKED, EXPIRED or VERIFIED)
358      * @throws CertificateException
359      */

360     public static String JavaDoc verifyCertificate(X509Certificate cert
361                                            , X509Certificate cacert
362                                            , X509CRL crl) throws CertificateException {
363
364         String JavaDoc status = "INVALID";
365
366         try {
367             if (crl.isRevoked(cert)) {
368                 status = "REVOKED";
369             } else {
370                 try {
371                     cert.checkValidity(new Date JavaDoc());
372                 } catch (Exception JavaDoc vae) {
373                     status = "EXPIRED";
374                 }
375
376                 if (!status.equals("EXPIRED")) {
377                     try {
378                         cert.verify(cacert.getPublicKey());
379                         status = "VERIFIED";
380                     } catch (Exception JavaDoc vee) {
381                         status = "INVALID";
382                     }
383                 }
384             }
385
386             return status;
387         } catch (Exception JavaDoc e) {
388             e.printStackTrace();
389             throw new CertificateException(e.getMessage());
390         }
391     }
392
393     /**
394      * Encodes a certificate as a PEM formatted string
395      *
396      * @param cert X.509 certificate
397      * @return certificate as PEM encoded string
398      * @throws CertificateEncodingException
399      */

400     public static String JavaDoc getCertificateAsPem(X509Certificate cert) throws CertificateEncodingException {
401
402         byte output[] = cert.getEncoded();
403         byte certB64[] = Base64.encode(output);
404
405         return "-----BEGIN CERTIFICATE-----\n" + new String JavaDoc(certB64) + "\n-----END CERTIFICATE-----";
406     }
407
408     /**
409      * Encodes a private key as a PEM formatted string
410      *
411      * @param privatekey private key
412      * @return private key as PEM encoded string
413      */

414     public static String JavaDoc getPrivateAsPem(PrivateKey privatekey) {
415
416         byte output[] = privatekey.getEncoded();
417         byte certB64[] = Base64.encode(output);
418
419         return "-----BEGIN PRIVATE KEY-----\n" + new String JavaDoc(certB64) + "\n-----END PRIVATE KEY-----";
420     }
421
422     /**
423      * Saves certificate and corresponding private key as a P12 keystore
424      *
425      * @param cert X.509 certificate
426      * @param signedby X.509 certificate of the signer
427      * @param privatekey private key
428      * @param keystore keystore filename and location
429      * @param entryname keystore entry name
430      * @param password keystore password
431      * @throws KeyStoreException P12 keystore error
432      * @throws NoSuchProviderException unknown JCE provider
433      * @throws Exception other errors
434      */

435     public static void saveAsP12(X509Certificate cert
436                                  , X509Certificate signedby
437                                  , PrivateKey privatekey
438                                  , String JavaDoc keystore
439                                  , String JavaDoc entryname
440                                  , StringBuffer JavaDoc password) throws KeyStoreException, NoSuchProviderException, Exception JavaDoc {
441
442         // Store certificate in PKCS#12 store
443
KeyStore store = KeyStore.getInstance("PKCS12", "BC");
444
445         store = KeyTools.createP12(entryname, privatekey, cert, signedby);
446         store.store(new FileOutputStream JavaDoc(keystore), password.toString().toCharArray());
447     }
448
449     /**
450      * Read certificate from PKCS12 keystore
451      *
452      * @param keystore keystore filename and location
453      * @param entryname keystore entry name
454      * @param password keystore password
455      * @return X.509 certificate
456      * @throws KeyStoreException P12 keystore error
457      * @throws NoSuchAlgorithmException unknown algorithm
458      * @throws NoSuchProviderException unknown provider
459      * @throws IOException I/O errors
460      * @throws CertificateException
461      */

462     public static X509Certificate getCertificateFromP12(String JavaDoc keystore
463                                                         , String JavaDoc entryname
464                                                         , StringBuffer JavaDoc password) throws KeyStoreException, NoSuchAlgorithmException, NoSuchProviderException, IOException JavaDoc, CertificateException {
465         // read keystore
466
KeyStore store = KeyStore.getInstance("PKCS12", "BC");
467         store.load(new FileInputStream JavaDoc(keystore), password.toString().toCharArray());
468
469         Certificate JavaDoc[] certchain = KeyTools.getCertChain(store, entryname);
470         return (X509Certificate) certchain[0];
471     }
472
473     /**
474      * Read CA certificate from PKCS12 keystore
475      *
476      * @param keystore keystore filename and location
477      * @param entryname keystore entry name
478      * @param password keystore password
479      * @return CA X.509 certificate
480      * @throws KeyStoreException P12 keystore error
481      * @throws NoSuchAlgorithmException unknown algorithm
482      * @throws NoSuchProviderException unknown provider
483      * @throws IOException I/O errors
484      * @throws CertificateException
485      */

486     public static X509Certificate getCACertificateFromP12(String JavaDoc keystore
487                                                           , String JavaDoc entryname
488                                                           , StringBuffer JavaDoc password) throws KeyStoreException, NoSuchAlgorithmException, NoSuchProviderException, IOException JavaDoc, CertificateException {
489         // read keystore
490
KeyStore store = KeyStore.getInstance("PKCS12", "BC");
491         store.load(new FileInputStream JavaDoc(keystore), password.toString().toCharArray());
492
493         Certificate JavaDoc[] certchain = KeyTools.getCertChain(store, entryname);
494         return (X509Certificate) certchain[certchain.length - 1];
495     }
496
497     /**
498      * Read private key from PKCS12 keystore
499      *
500      * @param keystore keystore filename and location
501      * @param entryname keystore entry name
502      * @param password keystore password
503      * @return private key
504      * @throws KeyStoreException P12 keystore error
505      * @throws NoSuchAlgorithmException unknown algorithm
506      * @throws NoSuchProviderException unknown provider
507      * @throws IOException I/O errors
508      * @throws CertificateException
509      * @throws UnrecoverableKeyException
510      */

511     public static PrivateKey getPrivateFromP12(String JavaDoc keystore
512                                                , String JavaDoc entryname
513                                                , StringBuffer JavaDoc password) throws KeyStoreException, NoSuchAlgorithmException, NoSuchProviderException, IOException JavaDoc, CertificateException, UnrecoverableKeyException {
514         // read keystore
515
KeyStore store = KeyStore.getInstance("PKCS12", "BC");
516         store.load(new FileInputStream JavaDoc(keystore), password.toString().toCharArray());
517
518         return (PrivateKey) store.getKey(entryname, password.toString().toCharArray());
519     }
520
521     /**
522      * Replaces all occurrences of a string in a text with another string
523      *
524      * @param text text
525      * @param repl string to replace
526      * @param with replacement string
527      * @return new string
528      */

529     public static String JavaDoc replace(String JavaDoc text, String JavaDoc repl, String JavaDoc with) {
530         if (text == null) {
531             return null;
532         }
533
534         StringBuffer JavaDoc buf = new StringBuffer JavaDoc(text.length());
535         int start = 0, end = 0;
536         while ((end = text.indexOf(repl, start)) != -1) {
537             buf.append(text.substring(start, end)).append(with);
538             start = end + repl.length();
539         }
540         buf.append(text.substring(start));
541         return buf.toString();
542     }
543
544     /**
545      * Reads a PKCS10 certification request from a PEM string
546      *
547      * @param request the certification request as a PEM string
548      * @return certification request
549      * @throws CertificateException
550      */

551     public static PKCS10CertificationRequest getPKCS10Request(String JavaDoc request) throws CertificateException {
552
553         byte[] buffer;
554
555         PKCS10CertificationRequest pkcs10 = null;
556
557         try {
558             try {
559                 // A real PKCS10 PEM request
560
String JavaDoc beginKey = "-----BEGIN CERTIFICATE REQUEST-----";
561                 String JavaDoc endKey = "-----END CERTIFICATE REQUEST-----";
562                 buffer = FileTools.getBytesFromPEM(request.getBytes(), beginKey, endKey);
563             } catch (IOException JavaDoc e) {
564                 try {
565                     // Keytool PKCS10 PEM request
566
String JavaDoc beginKey = "-----BEGIN NEW CERTIFICATE REQUEST-----";
567                     String JavaDoc endKey = "-----END NEW CERTIFICATE REQUEST-----";
568                     buffer = FileTools.getBytesFromPEM(request.getBytes(), beginKey, endKey);
569                 } catch (IOException JavaDoc ioe) {
570                     // IE PKCS10 Base64 coded request
571

572                     // FIX:IE generates cariage returns on Windows machines
573
// , so we strip them out (else we get an error)
574
request = replace(request, "\n", "");
575                     request = replace(request, "\r", "");
576
577                     buffer = Base64.decode(request.getBytes());
578                 }
579             }
580
581             DERObject derobj = new DERInputStream(new ByteArrayInputStream JavaDoc(buffer)).readObject();
582             ASN1Sequence seq = (ASN1Sequence) derobj;
583             pkcs10 = new PKCS10CertificationRequest(seq);
584
585             if (pkcs10.verify() == false) {
586                 throw new CertificateException("Not a valid PKCS10 request");
587             }
588
589             return pkcs10;
590
591         } catch (Exception JavaDoc e) {
592             e.printStackTrace();
593             throw new CertificateException(e.getMessage());
594         }
595     }
596
597     /**
598      * Reads a Netscape formatted certification request from a PEM string
599      *
600      * @param request the certification request as a PEM string
601      * @return certification request
602      * @throws CertificateException
603      */

604     public static NetscapeCertRequest getNetscapeRequest(String JavaDoc request) throws CertificateException {
605         byte[] buffer;
606
607         NetscapeCertRequest nscr = null;
608
609         try {
610             // FIX: Netscape/Mozilla generates cariage returns on Windows machines
611
// , so we strip them out (else we get an error)
612
request = replace(request, "\n", "");
613             request = replace(request, "\r", "");
614
615             buffer = Base64.decode(request.getBytes());
616
617             DERInputStream in = new DERInputStream(new ByteArrayInputStream JavaDoc(buffer));
618             DERSequence spkac = (DERSequence) in.readObject();
619             nscr = new NetscapeCertRequest(spkac);
620
621             nscr.setChallenge("challenge");
622             if (nscr.verify("challenge") == false) {
623                 throw new CertificateException("Not a valid Netscape request");
624             }
625
626             return nscr;
627
628         } catch (Exception JavaDoc e) {
629             e.printStackTrace();
630             throw new CertificateException(e.getMessage());
631         }
632     }
633 }
634
Popular Tags