KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ejbca > core > protocol > PKCS10RequestMessage


1 /*************************************************************************
2  * *
3  * EJBCA: The OpenSource Certificate Authority *
4  * *
5  * This software is free software; you can redistribute it and/or *
6  * modify it under the terms of the GNU Lesser General Public *
7  * License as published by the Free Software Foundation; either *
8  * version 2.1 of the License, or any later version. *
9  * *
10  * See terms of license at gnu.org. *
11  * *
12  *************************************************************************/

13
14 package org.ejbca.core.protocol;
15
16 import java.io.IOException JavaDoc;
17 import java.math.BigInteger JavaDoc;
18 import java.security.InvalidKeyException JavaDoc;
19 import java.security.NoSuchAlgorithmException JavaDoc;
20 import java.security.NoSuchProviderException JavaDoc;
21 import java.security.PrivateKey JavaDoc;
22 import java.security.PublicKey JavaDoc;
23 import java.security.SignatureException JavaDoc;
24 import java.security.cert.Certificate JavaDoc;
25 import java.security.cert.X509Certificate JavaDoc;
26 import java.util.Date JavaDoc;
27
28 import org.apache.log4j.Logger;
29 import org.bouncycastle.asn1.ASN1Set;
30 import org.bouncycastle.asn1.DEREncodable;
31 import org.bouncycastle.asn1.DERPrintableString;
32 import org.bouncycastle.asn1.DERString;
33 import org.bouncycastle.asn1.DERUTF8String;
34 import org.bouncycastle.asn1.cms.Attribute;
35 import org.bouncycastle.asn1.cms.AttributeTable;
36 import org.bouncycastle.asn1.pkcs.CertificationRequestInfo;
37 import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
38 import org.bouncycastle.asn1.x509.X509Extension;
39 import org.bouncycastle.asn1.x509.X509Extensions;
40 import org.bouncycastle.asn1.x509.X509Name;
41 import org.bouncycastle.cms.CMSSignedGenerator;
42 import org.bouncycastle.jce.PKCS10CertificationRequest;
43 import org.ejbca.util.CertTools;
44
45
46
47 /**
48  * Class to handle PKCS10 request messages sent to the CA.
49  *
50  * @version $Id: PKCS10RequestMessage.java,v 1.11.2.1 2007/03/28 12:26:54 anatom Exp $
51  */

52 public class PKCS10RequestMessage implements IRequestMessage {
53     /**
54      * Determines if a de-serialized file is compatible with this class.
55      *
56      * Maintainers must change this value if and only if the new version
57      * of this class is not compatible with old versions. See Sun docs
58      * for <a HREF=http://java.sun.com/products/jdk/1.1/docs/guide
59      * /serialization/spec/version.doc.html> details. </a>
60      *
61      */

62     static final long serialVersionUID = 3597275157018205137L;
63
64     private static final Logger log = Logger.getLogger(PKCS10RequestMessage.class);
65
66     /** Raw form of the PKCS10 message */
67     protected byte[] p10msg;
68
69     /** manually set password */
70     protected String JavaDoc password = null;
71
72     /** manually set username */
73     protected String JavaDoc username = null;
74     
75     /** If the CA certificate should be included in the reponse or not, default to true = yes */
76     protected boolean includeCACert = true;
77
78     /** preferred digest algorithm to use in replies, if applicable */
79     private transient String JavaDoc preferredDigestAlg = CMSSignedGenerator.DIGEST_SHA1;
80
81     /** The pkcs10 request message, not serialized. */
82     protected transient PKCS10CertificationRequest pkcs10 = null;
83
84     /** Type of error */
85     private int error = 0;
86
87     /** Error text */
88     private String JavaDoc errorText = null;
89
90     /**
91      * Constructs a new empty PKCS#10 message handler object.
92      *
93      * @throws IOException if the request can not be parsed.
94      */

95     public PKCS10RequestMessage() {
96         // No constructor
97
}
98
99     /**
100      * Constructs a new PKCS#10 message handler object.
101      *
102      * @param msg The DER encoded PKCS#10 request.
103      *
104      * @throws IOException if the request can not be parsed.
105      */

106     public PKCS10RequestMessage(byte[] msg) {
107         log.debug(">PKCS10RequestMessage(byte[])");
108         this.p10msg = msg;
109         init();
110         log.debug("<PKCS10RequestMessage(byte[])");
111     }
112
113     /**
114      * Constructs a new PKCS#10 message handler object.
115      *
116      * @param p10 the PKCS#10 request
117      */

118     public PKCS10RequestMessage(PKCS10CertificationRequest p10) {
119         log.debug(">PKCS10RequestMessage(ExtendedPKCS10CertificationRequest)");
120         p10msg = p10.getEncoded();
121         pkcs10 = p10;
122         log.debug("<PKCS10RequestMessage(ExtendedPKCS10CertificationRequest)");
123     }
124
125     private void init() {
126         pkcs10 = new PKCS10CertificationRequest(p10msg);
127     }
128
129     /**
130      * DOCUMENT ME!
131      *
132      * @return DOCUMENT ME!
133      *
134      * @throws InvalidKeyException DOCUMENT ME!
135      * @throws NoSuchAlgorithmException DOCUMENT ME!
136      * @throws NoSuchProviderException DOCUMENT ME!
137      */

138     public PublicKey JavaDoc getRequestPublicKey()
139             throws InvalidKeyException JavaDoc, NoSuchAlgorithmException JavaDoc, NoSuchProviderException JavaDoc {
140         try {
141             if (pkcs10 == null) {
142                 init();
143             }
144         } catch (IllegalArgumentException JavaDoc e) {
145             log.error("PKCS10 not inited!");
146
147             return null;
148         }
149
150         return pkcs10.getPublicKey();
151     }
152
153     /** force a password, i.e. ignore the challenge password in the request
154      */

155     public void setPassword(String JavaDoc pwd) {
156         this.password = pwd;
157     }
158
159     /**
160      * Returns the challenge password from the certificattion request.
161      *
162      * @return challenge password from certification request or null if none exist in the request.
163      */

164     public String JavaDoc getPassword() {
165         if (password != null)
166             return password;
167         try {
168             if (pkcs10 == null) {
169                 init();
170             }
171         } catch (IllegalArgumentException JavaDoc e) {
172             log.error("PKCS10 not inited!");
173             return null;
174         }
175
176         String JavaDoc ret = null;
177
178         // Get attributes
179
// The password attribute can be either a pkcs_9_at_challengePassword directly
180
// or
181
// a pkcs_9_at_extensionRequest containing a pkcs_9_at_challengePassword as a
182
// X509Extension.
183
CertificationRequestInfo info = pkcs10.getCertificationRequestInfo();
184         AttributeTable attributes = new AttributeTable(info.getAttributes());
185         if (attributes == null) {
186             return null;
187         }
188         Attribute attr = attributes.get(PKCSObjectIdentifiers.pkcs_9_at_challengePassword);
189         DEREncodable obj = null;
190         if (attr == null) {
191             // See if we have it embedded in an extension request instead
192
attr = attributes.get(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
193             if (attr == null) {
194                 return null;
195             }
196             log.debug("got extension request");
197             ASN1Set values = attr.getAttrValues();
198             if (values.size() == 0) {
199                 return null;
200             }
201             X509Extensions exts = X509Extensions.getInstance(values.getObjectAt(0));
202             X509Extension ext = exts.getExtension(PKCSObjectIdentifiers.pkcs_9_at_challengePassword);
203             if (ext == null) {
204                 log.debug("no challenge password extension");
205                 return null;
206             }
207             obj = ext.getValue();
208         } else {
209             // If it is a challengePassword directly, it's just to grab the value
210
ASN1Set values = attr.getAttrValues();
211             obj = values.getObjectAt(0);
212         }
213
214         if (obj != null) {
215             DERString str = null;
216
217             try {
218                 str = DERPrintableString.getInstance((obj));
219             } catch (IllegalArgumentException JavaDoc ie) {
220                 // This was not printable string, should be utf8string then according to pkcs#9 v2.0
221
str = DERUTF8String.getInstance((obj));
222             }
223
224             if (str != null) {
225                 ret = str.getString();
226             }
227         }
228
229         return ret;
230     }
231
232     /** force a username, i.e. ignore the DN/username in the request
233      */

234     public void setUsername(String JavaDoc username) {
235         this.username = username;
236     }
237
238     /**
239      * Returns the string representation of the CN field from the DN of the certification request,
240      * to be used as username.
241      *
242      * @return username, which is the CN field from the subject DN in certification request.
243      */

244     public String JavaDoc getUsername() {
245         if (username != null)
246             return username;
247         String JavaDoc name = CertTools.getPartFromDN(getRequestDN(), "CN");
248         if (name == null) {
249             log.error("No CN in DN: "+getRequestDN());
250             return null;
251         }
252         // Special if the DN contains unstructuredAddress where it becomes:
253
// CN=pix.primekey.se + unstructuredAddress=pix.primekey.se
254
// We only want the CN and not the oid-part.
255
String JavaDoc ret = name;
256         if (name != null) {
257             int index = name.indexOf(' ');
258             if (index > 0) {
259                 ret = name.substring(0, index);
260             } else {
261                 // Perhaps there is no space, only +
262
index = name.indexOf('+');
263                 if (index > 0) {
264                     ret = name.substring(0, index);
265                 }
266             }
267         }
268         log.debug("UserName='" + ret + "'");
269         return ret;
270     }
271
272     /**
273      * Gets the issuer DN if contained in the request (the CA the request is targeted at).
274      *
275      * @return issuerDN of receiving CA or null.
276      */

277     public String JavaDoc getIssuerDN() {
278         return null;
279     }
280
281     /**
282      * Gets the number (of CA cert) from IssuerAndSerialNumber. Combined with getIssuerDN to identify
283      * the CA-certificate of the CA the request is targeted for.
284      *
285      * @return serial number of CA certificate for CA issuing CRL or null.
286      */

287     public BigInteger JavaDoc getSerialNo() {
288         return null;
289     }
290     
291     /**
292      * Gets the issuer DN (of CA cert) from IssuerAndSerialNumber when this is a CRL request.
293      *
294      * @return issuerDN of CA issuing CRL.
295      */

296     public String JavaDoc getCRLIssuerDN() {
297         return null;
298     }
299
300     /**
301      * Gets the number (of CA cert) from IssuerAndSerialNumber when this is a CRL request.
302      *
303      * @return serial number of CA certificate for CA issuing CRL.
304      */

305     public BigInteger JavaDoc getCRLSerialNo() {
306         return null;
307     }
308
309     /**
310      * Returns the string representation of the subject DN from the certification request.
311      *
312      * @return subject DN from certification request or null.
313      */

314     public String JavaDoc getRequestDN() {
315         try {
316             if (pkcs10 == null) {
317                 init();
318             }
319         } catch (IllegalArgumentException JavaDoc e) {
320             log.error("PKCS10 not inited!");
321             return null;
322         }
323
324         String JavaDoc ret = null;
325
326         // Get subject name from request
327
CertificationRequestInfo info = pkcs10.getCertificationRequestInfo();
328
329         if (info != null) {
330             X509Name name = info.getSubject();
331             ret = name.toString();
332         }
333
334         return ret;
335     }
336
337     public String JavaDoc getRequestAltNames() {
338         return null;
339     }
340
341     /**
342      * @see org.ejbca.core.protocol.IRequestMessage
343      */

344     public Date JavaDoc getRequestValidityNotBefore() {
345         return null;
346     }
347     
348     /**
349      * @see org.ejbca.core.protocol.IRequestMessage
350      */

351     public Date JavaDoc getRequestValidityNotAfter() {
352         return null;
353     }
354     
355     /**
356      * Gets the underlying BC <code>PKCS10CertificationRequest</code> object.
357      *
358      * @return the request object
359      */

360     public PKCS10CertificationRequest getCertificationRequest() {
361         try {
362             if (pkcs10 == null) {
363                 init();
364             }
365         } catch (IllegalArgumentException JavaDoc e) {
366             log.error("PKCS10 not inited!");
367
368             return null;
369         }
370
371         return pkcs10;
372     }
373
374     /**
375      * DOCUMENT ME!
376      *
377      * @return DOCUMENT ME!
378      *
379      * @throws InvalidKeyException DOCUMENT ME!
380      * @throws NoSuchAlgorithmException DOCUMENT ME!
381      * @throws NoSuchProviderException DOCUMENT ME!
382      */

383     public boolean verify()
384     throws InvalidKeyException JavaDoc, NoSuchAlgorithmException JavaDoc, NoSuchProviderException JavaDoc {
385         return verify(null);
386     }
387     public boolean verify(PublicKey JavaDoc pubKey)
388             throws InvalidKeyException JavaDoc, NoSuchAlgorithmException JavaDoc, NoSuchProviderException JavaDoc {
389         log.debug(">verify()");
390
391         boolean ret = false;
392
393         try {
394             if (pkcs10 == null) {
395                 init();
396             }
397             if (pubKey == null) {
398                 ret = pkcs10.verify();
399             } else {
400                 ret = pkcs10.verify(pubKey, "BC");
401             }
402         } catch (IllegalArgumentException JavaDoc e) {
403             log.error("PKCS10 not inited!");
404         } catch (InvalidKeyException JavaDoc e) {
405             log.error("Error in PKCS10-request:", e);
406             throw e;
407         } catch (SignatureException JavaDoc e) {
408             log.error("Error in PKCS10-signature:", e);
409         }
410
411         log.debug("<verify()");
412
413         return ret;
414     }
415
416     /**
417      * indicates if this message needs recipients public and private key to verify, decrypt etc. If
418      * this returns true, setKeyInfo() should be called.
419      *
420      * @return True if public and private key is needed.
421      */

422     public boolean requireKeyInfo() {
423         return false;
424     }
425
426     /**
427      * Sets the public and private key needed to decrypt/verify the message. Must be set if
428      * requireKeyInfo() returns true.
429      *
430      * @param cert certificate containing the public key.
431      * @param key private key.
432      * @param provider the provider to use, if the private key is on a HSM you must use a special provider. If null is given, the default BC provider is used.
433      *
434      * @see #requireKeyInfo()
435      */

436     public void setKeyInfo(X509Certificate JavaDoc cert, PrivateKey JavaDoc key, String JavaDoc Provider) {
437     }
438
439     /**
440      * Returns an error number after an error has occured processing the request
441      *
442      * @return class specific error number
443      */

444     public int getErrorNo() {
445         return error;
446     }
447
448     /**
449      * Returns an error message after an error has occured processing the request
450      *
451      * @return class specific error message
452      */

453     public String JavaDoc getErrorText() {
454         return errorText;
455     }
456
457     /**
458      * Returns a senderNonce if present in the request
459      *
460      * @return senderNonce
461      */

462     public String JavaDoc getSenderNonce() {
463         return null;
464     }
465
466     /**
467      * Returns a transaction identifier if present in the request
468      *
469      * @return transaction id
470      */

471     public String JavaDoc getTransactionId() {
472         return null;
473     }
474
475     /**
476      * Returns requesters key info, key id or similar
477      *
478      * @return request key info
479      */

480     public byte[] getRequestKeyInfo() {
481         return null;
482     }
483     
484     /** @see org.ejbca.core.protocol.IRequestMessage
485      */

486     public String JavaDoc getPreferredDigestAlg() {
487         return preferredDigestAlg;
488     }
489     /** @see org.ejbca.core.protocol.IRequestMessage
490      */

491     public boolean includeCACert() {
492         return includeCACert;
493     }
494
495     /** @see org.ejbca.core.protocol.IRequestMessage
496      */

497     public int getRequestType() {
498         return 0;
499     }
500     
501     /** @see org.ejbca.core.protocol.IRequestMessage
502      */

503     public int getRequestId() {
504         return 0;
505     }
506     
507     /** @see org.ejbca.core.protocol.IRequestMessage
508      */

509     public IResponseMessage createResponseMessage(Class JavaDoc responseClass, IRequestMessage req, Certificate JavaDoc cert, PrivateKey JavaDoc signPriv, PrivateKey JavaDoc encPriv, String JavaDoc provider) {
510         return RequestMessageUtils.createResponseMessage(responseClass, req, cert, signPriv, encPriv, provider);
511     }
512 } // PKCS10RequestMessage
513
Popular Tags