KickJava   Java API By Example, From Geeks To Geeks.

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


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.ByteArrayInputStream JavaDoc;
17 import java.io.ByteArrayOutputStream JavaDoc;
18 import java.io.IOException JavaDoc;
19 import java.math.BigInteger JavaDoc;
20 import java.security.GeneralSecurityException JavaDoc;
21 import java.security.InvalidKeyException JavaDoc;
22 import java.security.NoSuchAlgorithmException JavaDoc;
23 import java.security.NoSuchProviderException JavaDoc;
24 import java.security.PrivateKey JavaDoc;
25 import java.security.PublicKey JavaDoc;
26 import java.security.cert.CertificateException JavaDoc;
27 import java.security.cert.X509Certificate JavaDoc;
28 import java.util.Collection JavaDoc;
29 import java.util.Enumeration JavaDoc;
30 import java.util.Iterator JavaDoc;
31
32 import org.apache.log4j.Logger;
33 import org.bouncycastle.asn1.ASN1InputStream;
34 import org.bouncycastle.asn1.ASN1OctetString;
35 import org.bouncycastle.asn1.ASN1Sequence;
36 import org.bouncycastle.asn1.ASN1Set;
37 import org.bouncycastle.asn1.DEREncodable;
38 import org.bouncycastle.asn1.DERObject;
39 import org.bouncycastle.asn1.DEROctetString;
40 import org.bouncycastle.asn1.DEROutputStream;
41 import org.bouncycastle.asn1.DERPrintableString;
42 import org.bouncycastle.asn1.cms.Attribute;
43 import org.bouncycastle.asn1.cms.CMSObjectIdentifiers;
44 import org.bouncycastle.asn1.cms.ContentInfo;
45 import org.bouncycastle.asn1.cms.EnvelopedData;
46 import org.bouncycastle.asn1.cms.IssuerAndSerialNumber;
47 import org.bouncycastle.asn1.cms.KeyTransRecipientInfo;
48 import org.bouncycastle.asn1.cms.RecipientIdentifier;
49 import org.bouncycastle.asn1.cms.RecipientInfo;
50 import org.bouncycastle.asn1.cms.SignedData;
51 import org.bouncycastle.asn1.cms.SignerInfo;
52 import org.bouncycastle.cms.CMSEnvelopedData;
53 import org.bouncycastle.cms.CMSException;
54 import org.bouncycastle.cms.CMSSignedData;
55 import org.bouncycastle.cms.CMSSignedGenerator;
56 import org.bouncycastle.cms.RecipientInformation;
57 import org.bouncycastle.cms.RecipientInformationStore;
58 import org.bouncycastle.cms.SignerInformation;
59 import org.bouncycastle.cms.SignerInformationStore;
60 import org.bouncycastle.jce.PKCS10CertificationRequest;
61 import org.ejbca.util.Base64;
62 import org.ejbca.util.CertTools;
63
64
65 /**
66  * Class to handle SCEP request messages sent to the CA.
67  * TODO: don't forget extensions, e.g. KeyUsage requested by end entity
68  *
69  * @version $Id: ScepRequestMessage.java,v 1.7.2.1 2007/03/29 15:04:59 anatom Exp $
70  */

71 public class ScepRequestMessage extends PKCS10RequestMessage implements IRequestMessage {
72     /**
73      * Determines if a de-serialized file is compatible with this class.
74      *
75      * Maintainers must change this value if and only if the new version
76      * of this class is not compatible with old versions. See Sun docs
77      * for <a HREF=http://java.sun.com/products/jdk/1.1/docs/guide
78      * /serialization/spec/version.doc.html> details. </a>
79      *
80      */

81     static final long serialVersionUID = -235623330828902051L;
82
83     private static Logger log = Logger.getLogger(ScepRequestMessage.class);
84
85     public static final String JavaDoc id_Verisign = "2.16.840.1.113733";
86     public static final String JavaDoc id_pki = id_Verisign + ".1";
87     public static final String JavaDoc id_attributes = id_pki + ".9";
88     public static final String JavaDoc id_messageType = id_attributes + ".2";
89     public static final String JavaDoc id_pkiStatus = id_attributes + ".3";
90     public static final String JavaDoc id_failInfo = id_attributes + ".4";
91     public static final String JavaDoc id_senderNonce = id_attributes + ".5";
92     public static final String JavaDoc id_recipientNonce = id_attributes + ".6";
93     public static final String JavaDoc id_transId = id_attributes + ".7";
94     public static final String JavaDoc id_extensionReq = id_attributes + ".8";
95
96     /** Raw form of the Scep message */
97     private byte[] scepmsg;
98
99     /**
100      * The messageType attribute specify the type of operation performed by the transaction. This
101      * attribute is required in all PKI messages. Currently, the following message types are
102      * defined:
103      * PKCSReq (19) -- Permits use of PKCS#10 certificate request
104      * CertRep (3) -- Response to certificate or CRL request
105      * GetCertInitial (20) -- Certificate polling in manual enrollment
106      * GetCert (21) -- Retrieve a certificate
107      * GetCRL (22) -- Retrieve a CRL
108      */

109     private int messageType = 0;
110     public static int SCEP_TYPE_PKCSREQ = 19;
111     public static int SCEP_TYPE_GETCERTINITIAL = 20; // Used when request is in pending state.
112
public static int SCEP_TYPE_GETCRL = 22;
113     public static int SCEP_TYPE_GETCERT = 21;
114
115     /**
116      * SenderNonce in a request is used as recipientNonce when the server sends back a reply to the
117      * client. This is base64 encoded bytes
118      */

119     private String JavaDoc senderNonce = null;
120
121     /** transaction id */
122     private String JavaDoc transactionId = null;
123
124     /** request key info, this is the requestors self-signed certificate used to identify the senders public key */
125     private byte[] requestKeyInfo = null;
126
127     /** Type of error */
128     private int error = 0;
129
130     /** Error text */
131     private String JavaDoc errorText = null;
132     
133     /** Issuer DN the message is sent to (CAs Issuer DN), contained in the
134      * request as recipientInfo.issuerAndSerialNumber in EnvelopeData part */

135     private transient String JavaDoc issuerDN = null;
136     
137     /** SerialNumber of the CA cert of the CA the message is sent to, contained in the
138      * request as recipientInfo.issuerAndSerialNumber in EnvelopeData part */

139     private transient BigInteger JavaDoc serialNo = null;
140
141     /** Signed data, the whole enchilada to to speak... */
142     private transient SignedData sd = null;
143
144     /** Enveloped data, carrying the 'beef' of the request */
145     private transient EnvelopedData envData = null;
146
147     /** Enveloped data, carrying the 'beef' of the request */
148     private transient ContentInfo envEncData = null;
149
150     /** Private key used for decryption. */
151     private transient PrivateKey JavaDoc privateKey = null;
152     /** JCE Provider used when decrypting with private key. Default provider is BC. */
153     private transient String JavaDoc jceProvider = "BC";
154
155     /** IssuerAndSerialNUmber for CRL request */
156     private transient IssuerAndSerialNumber issuerAndSerno = null;
157
158     /** preferred digest algorithm to use in replies, if applicable */
159     private transient String JavaDoc preferredDigestAlg = CMSSignedGenerator.DIGEST_MD5;
160
161     private transient X509Certificate JavaDoc signercert;
162
163     /**
164      * Constructs a new SCEP/PKCS7 message handler object.
165      *
166      * @param msg The DER encoded PKCS7 request.
167      * @param incCACert if the CA certificate should be included in the response or not
168      *
169      * @throws IOException if the request can not be parsed.
170      */

171     public ScepRequestMessage(byte[] msg, boolean incCACert) throws IOException JavaDoc {
172         log.debug(">ScepRequestMessage");
173         this.scepmsg = msg;
174         this.includeCACert = incCACert;
175         init();
176         log.debug("<ScepRequestMessage");
177     }
178
179     private void init() throws IOException JavaDoc {
180         log.debug(">init");
181
182         try {
183             CMSSignedData csd = new CMSSignedData(scepmsg);
184             SignerInformationStore infoStore = csd.getSignerInfos();
185             Collection JavaDoc signers = infoStore.getSigners();
186             Iterator JavaDoc iter = signers.iterator();
187             if (iter.hasNext()) {
188                 SignerInformation si = (SignerInformation)iter.next();
189                 preferredDigestAlg = si.getDigestAlgOID();
190                 log.debug("Set "+ preferredDigestAlg+" as preferred digest algorithm for SCEP");
191             }
192         } catch (CMSException e) {
193             // ignore, use default digest algo
194
log.error("CMSException trying to get preferred digest algorithm: ", e);
195         }
196         // Parse and verify the entegrity of the PKIOperation message PKCS#7
197
/* If this would have been done using the newer CMS it would have made me so much happier... */
198         ASN1Sequence seq = (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream JavaDoc(scepmsg)).readObject();
199         ContentInfo ci = new ContentInfo(seq);
200         String JavaDoc ctoid = ci.getContentType().getId();
201
202         if (ctoid.equals(CMSObjectIdentifiers.signedData.getId())) {
203             // This is SignedData so it is a pkcsCertReqSigned,
204
// pkcsGetCertInitialSigned, pkcsGetCertSigned, pkcsGetCRLSigned
205
// (could also be pkcsRepSigned or certOnly, but we don't receive them on the server side
206
// Try to find out what kind of message this is
207
sd = new SignedData((ASN1Sequence) ci.getContent());
208
209             // Get self signed cert to identify the senders public key
210
ASN1Set certs = sd.getCertificates();
211             if (certs.size() > 0) {
212                 // There should be only one...
213
DEREncodable dercert = certs.getObjectAt(0);
214                 if (dercert != null) {
215                     // Requestors self-signed certificate is requestKeyInfo
216
ByteArrayOutputStream JavaDoc bOut = new ByteArrayOutputStream JavaDoc();
217                     DEROutputStream dOut = new DEROutputStream(bOut);
218                     dOut.writeObject(dercert);
219                     if (bOut.size() > 0) {
220                         requestKeyInfo = bOut.toByteArray();
221                         //Create Certificate used for debugging
222
try {
223                             signercert = CertTools.getCertfromByteArray(requestKeyInfo);
224                             log.debug("requestKeyInfo is SubjectDN: " + signercert.getSubjectDN().toString() +
225                                     ", Serial=" + signercert.getSerialNumber().toString(16) +
226                                     "; IssuerDN: "+ signercert.getIssuerDN().toString());
227                         } catch (CertificateException JavaDoc e) {
228                             log.error("Error parsing requestKeyInfo : ", e);
229                         }
230                         
231                     }
232                 }
233             }
234
235             Enumeration JavaDoc sis = sd.getSignerInfos().getObjects();
236
237             if (sis.hasMoreElements()) {
238                 SignerInfo si = new SignerInfo((ASN1Sequence) sis.nextElement());
239                 Enumeration JavaDoc attr = si.getAuthenticatedAttributes().getObjects();
240
241                 while (attr.hasMoreElements()) {
242                     Attribute a = new Attribute((ASN1Sequence) attr.nextElement());
243
244                     log.debug("Found attribute: " + a.getAttrType().getId());
245
246                     if (a.getAttrType().getId().equals(id_senderNonce)) {
247                         Enumeration JavaDoc values = a.getAttrValues().getObjects();
248                         ASN1OctetString str = ASN1OctetString.getInstance(values.nextElement());
249                         senderNonce = new String JavaDoc(Base64.encode(str.getOctets(), false));
250                         log.debug("senderNonce = " + senderNonce);
251                     }
252                     if (a.getAttrType().getId().equals(id_transId)) {
253                         Enumeration JavaDoc values = a.getAttrValues().getObjects();
254                         DERPrintableString str = DERPrintableString.getInstance(values.nextElement());
255                         transactionId = str.getString();
256                         log.debug("transactionId = " + transactionId);
257                     }
258                     if (a.getAttrType().getId().equals(id_messageType)) {
259                         Enumeration JavaDoc values = a.getAttrValues().getObjects();
260                         DERPrintableString str = DERPrintableString.getInstance(values.nextElement());
261                         messageType = Integer.parseInt(str.getString());
262                         log.debug("messagetype = " + messageType);
263                     }
264                 }
265             }
266
267             // If this is a PKCSReq
268
if ((messageType == ScepRequestMessage.SCEP_TYPE_PKCSREQ) || (messageType == ScepRequestMessage.SCEP_TYPE_GETCRL) || (messageType == ScepRequestMessage.SCEP_TYPE_GETCERTINITIAL)) {
269                 // Extract the contents, which is an encrypted PKCS10 if messageType == 19
270
// , and an encrypted issuer and subject if messageType == 20 (not extracted)
271
// and an encrypted IssuerAndSerialNumber if messageType == 22
272
ci = sd.getEncapContentInfo();
273                 ctoid = ci.getContentType().getId();
274
275                 if (ctoid.equals(CMSObjectIdentifiers.data.getId())) {
276                     DEROctetString content = (DEROctetString) ci.getContent();
277                     log.debug("envelopedData is " + content.getOctets().length + " bytes.");
278
279                     ASN1Sequence seq1 = (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream JavaDoc(content.getOctets())).readObject();
280                     envEncData = new ContentInfo(seq1);
281                     ctoid = envEncData.getContentType().getId();
282
283                     if (ctoid.equals(CMSObjectIdentifiers.envelopedData.getId())) {
284                         envData = new EnvelopedData((ASN1Sequence) envEncData.getContent());
285                         ASN1Set recipientInfos = envData.getRecipientInfos();
286                         Enumeration JavaDoc e = recipientInfos.getObjects();
287                         while (e.hasMoreElements()) {
288                             RecipientInfo ri = RecipientInfo.getInstance(e.nextElement());
289                             KeyTransRecipientInfo recipientInfo = KeyTransRecipientInfo.getInstance(ri.getInfo());
290                             RecipientIdentifier rid = recipientInfo.getRecipientIdentifier();
291                             IssuerAndSerialNumber iasn = IssuerAndSerialNumber.getInstance(rid.getId());
292                             issuerDN = iasn.getName().toString();
293                             serialNo = iasn.getSerialNumber().getValue();
294                             log.debug("IssuerDN: " + issuerDN);
295                             log.debug("SerialNumber: " + iasn.getSerialNumber().getValue().toString(16));
296                         }
297                     } else {
298                         errorText = "EncapsulatedContentInfo does not contain PKCS7 envelopedData: ";
299                         log.error(errorText + ctoid);
300                         error = 2;
301                     }
302                 } else {
303                     errorText = "EncapsulatedContentInfo is not of type 'data': ";
304                     log.error(errorText + ctoid);
305                     error = 3;
306                 }
307             } else {
308                 errorText = "This is not a certification request!";
309                 log.error(errorText);
310                 error = 4;
311             }
312         } else {
313             errorText = "PKCSReq does not contain 'signedData': ";
314             log.error(errorText + ctoid);
315             error = 1;
316         }
317
318         log.debug("<init");
319     } // init
320

321     private void decrypt() throws CMSException, NoSuchProviderException JavaDoc, GeneralSecurityException JavaDoc, IOException JavaDoc {
322         log.debug(">decrypt");
323
324         // Now we are getting somewhere (pheew),
325
// Now we just have to get the damn key...to decrypt the PKCS10
326
if (privateKey == null) {
327             errorText = "Need private key to decrypt!";
328             error = 5;
329             log.error(errorText);
330             return;
331         }
332
333         if (envEncData == null) {
334             errorText = "No enveloped data to decrypt!";
335             error = 6;
336             log.error(errorText);
337             return;
338         }
339
340         CMSEnvelopedData ed = new CMSEnvelopedData(envEncData);
341         RecipientInformationStore recipients = ed.getRecipientInfos();
342         Collection JavaDoc c = recipients.getRecipients();
343         Iterator JavaDoc it = c.iterator();
344         byte[] decBytes = null;
345
346         while (it.hasNext()) {
347             RecipientInformation recipient = (RecipientInformation) it.next();
348             log.debug("Privatekey : " + privateKey.getAlgorithm());
349             decBytes = recipient.getContent(privateKey, jceProvider);
350             break;
351         }
352
353         DERObject derobj = new ASN1InputStream(new ByteArrayInputStream JavaDoc(decBytes)).readObject();
354         if (messageType == ScepRequestMessage.SCEP_TYPE_PKCSREQ) {
355             ASN1Sequence seq = (ASN1Sequence) derobj;
356             pkcs10 = new PKCS10CertificationRequest(seq);
357             log.debug("Successfully extracted PKCS10.");
358             //log.debug("Successfully extracted PKCS10:"+new String(Base64.encode(pkcs10.getEncoded())));
359
}
360         if (messageType == ScepRequestMessage.SCEP_TYPE_GETCRL) {
361             issuerAndSerno = IssuerAndSerialNumber.getInstance(derobj);
362             log.debug("Successfully extracted IssuerAndSerialNumber.");
363         }
364         log.debug("<decrypt");
365     } // decrypt
366

367     /**
368      * Returns the public key from the certificattion request.
369      *
370      * @return public key from certification request.
371      */

372     public PublicKey JavaDoc getRequestPublicKey() {
373         log.debug(">getRequestPublicKey()");
374         PublicKey JavaDoc ret = null;
375         try {
376             if (envData == null) {
377                 init();
378                 decrypt();
379             }
380             ret = super.getRequestPublicKey();
381         } catch (IOException JavaDoc e) {
382             log.error("PKCS7 not inited!");
383         } catch (GeneralSecurityException JavaDoc e) {
384             log.error("Error in PKCS7:", e);
385         } catch (CMSException e) {
386             log.error("Error in PKCS7:", e);
387         }
388         log.debug("<getRequestPublicKey()");
389         return ret;
390     }
391
392     /**
393      * Verifies signatures, popo etc on the request message. If verification fails the request
394      * should be considered invalid.
395      *
396      * @return True if verification was successful, false if it failed.
397      *
398      * @throws InvalidKeyException If the key used for verification is invalid.
399      * @throws NoSuchProviderException if there is an error with the Provider.
400      * @throws NoSuchAlgorithmException if the signature on the request is done with an unhandled
401      * algorithm.
402      */

403     public boolean verify() {
404         log.debug(">verify()");
405         boolean ret = false;
406         try {
407             if (pkcs10 == null) {
408                 init();
409                 decrypt();
410             }
411             ret = super.verify();
412         } catch (IOException JavaDoc e) {
413             log.error("PKCS7 not inited!");
414         } catch (GeneralSecurityException JavaDoc e) {
415             log.error("Error in PKCS7:", e);
416         } catch (CMSException e) {
417             log.error("Error in PKCS7:", e);
418         }
419         log.debug("<verify()");
420         return ret;
421     }
422
423     /**
424      * Returns the challenge password from the certificattion request.
425      *
426      * @return challenge password from certification request.
427      */

428     public String JavaDoc getPassword() {
429         log.debug(">getPassword()");
430         String JavaDoc ret = null;
431         try {
432             if (pkcs10 == null) {
433                 init();
434                 decrypt();
435             }
436             ret = super.getPassword();
437         } catch (IOException JavaDoc e) {
438             log.error("PKCS7 not inited!");
439         } catch (GeneralSecurityException JavaDoc e) {
440             log.error("Error in PKCS7:", e);
441         } catch (CMSException e) {
442             log.error("Error in PKCS7:", e);
443         }
444         log.debug("<getPassword()");
445         return ret;
446     }
447
448     /**
449      * Returns the string representation of the CN field from the DN of the certification request,
450      * to be used as username.
451      *
452      * @return username, which is the CN field from the subject DN in certification request.
453      */

454     public String JavaDoc getUsername() {
455         log.debug(">getUsername()");
456         String JavaDoc ret = null;
457         try {
458             if (pkcs10 == null) {
459                 init();
460                 decrypt();
461             }
462             ret = super.getUsername();
463             if (ret == null) {
464                 // For Cisco boxes they can sometimes send DN as SN instead of CN
465
String JavaDoc name = CertTools.getPartFromDN(getRequestDN(), "SN");
466                 if (name == null) {
467                     log.error("No SN in DN: "+getRequestDN());
468                     return null;
469                 }
470                 // Special if the DN contains unstructuredAddress where it becomes:
471
// SN=1728668 + 1.2.840.113549.1.9.2=pix.primekey.se
472
// We only want the SN and not the oid-part.
473
int index = name.indexOf(' ');
474                 ret = name;
475                 if (index > 0) {
476                     ret = name.substring(0,index);
477                 } else {
478                     // Perhaps there is no space, only +
479
index = name.indexOf('+');
480                     if (index > 0) {
481                         ret = name.substring(0, index);
482                     }
483                 }
484             }
485         } catch (IOException JavaDoc e) {
486             log.error("PKCS7 not inited!");
487         } catch (GeneralSecurityException JavaDoc e) {
488             log.error("Error in PKCS7:", e);
489         } catch (CMSException e) {
490             log.error("Error in PKCS7:", e);
491         }
492         log.debug("<getUsername(): " + ret);
493         return ret;
494     }
495
496     /**
497      * Gets the issuer DN if contained in the request (the CA the request is targeted at).
498      *
499      * @return issuerDN of receiving CA or null.
500      */

501     public String JavaDoc getIssuerDN() {
502         log.debug(">getIssuerDN()");
503         String JavaDoc ret = null;
504         try {
505             if (envData == null) {
506                 init();
507             }
508             ret = issuerDN;
509         } catch (IOException JavaDoc e) {
510             log.error("PKCS7 not inited!");
511         }
512         log.debug("<getIssuerDN(): " + ret);
513         return ret;
514     }
515
516     /**
517      * Gets the issuer DN if contained in the request (the CA the request is targeted at).
518      *
519      * @return issuerDN of receiving CA or null.
520      */

521     public BigInteger JavaDoc getSerialNo() {
522         log.debug(">getSerialNo()");
523         // Use another method to do the decryption etc...
524
getIssuerDN();
525         return serialNo;
526     }
527     
528     /**
529      * Gets the issuer DN (of CA cert) from IssuerAndSerialNumber when this is a CRL request.
530      *
531      * @return issuerDN of CA issuing CRL.
532      */

533     public String JavaDoc getCRLIssuerDN() {
534         log.debug(">getCRLIssuerDN()");
535         String JavaDoc ret = null;
536         try {
537             if (issuerAndSerno == null) {
538                 init();
539                 decrypt();
540             }
541             ret = CertTools.stringToBCDNString(issuerAndSerno.getName().toString());
542         } catch (IOException JavaDoc e) {
543             log.error("PKCS7 not inited!");
544         } catch (GeneralSecurityException JavaDoc e) {
545             log.error("Error in PKCS7:", e);
546         } catch (CMSException e) {
547             log.error("Error in PKCS7:", e);
548         }
549         log.debug("<getCRLIssuerDN(): " + ret);
550         return ret;
551     }
552
553     /**
554      * Gets the number (of CA cert) from IssuerAndSerialNumber when this is a CRL request.
555      *
556      * @return serial number of CA certificate for CA issuing CRL.
557      */

558     public BigInteger JavaDoc getCRLSerialNo() {
559         log.debug(">getCRLSerialNo()");
560         BigInteger JavaDoc ret = null;
561         try {
562             if (issuerAndSerno == null) {
563                 init();
564                 decrypt();
565             }
566             ret = issuerAndSerno.getSerialNumber().getValue();
567         } catch (IOException JavaDoc e) {
568             log.error("PKCS7 not inited!");
569         } catch (GeneralSecurityException JavaDoc e) {
570             log.error("Error in PKCS7:", e);
571         } catch (CMSException e) {
572             log.error("Error in PKCS7:", e);
573         }
574         log.debug("<getCRLSerialNo(): " + ret);
575         return ret;
576     }
577
578     /**
579      * Returns the string representation of the subject DN from the certification request.
580      *
581      * @return subject DN from certification request.
582      */

583     public String JavaDoc getRequestDN() {
584         log.debug(">getRequestDN()");
585         String JavaDoc ret = null;
586         try {
587             if (pkcs10 == null) {
588                 init();
589                 decrypt();
590             }
591             ret = super.getRequestDN();
592         } catch (IOException JavaDoc e) {
593             log.error("PKCS7 not inited!");
594         } catch (GeneralSecurityException JavaDoc e) {
595             log.error("Error in PKCS7:", e);
596         } catch (CMSException e) {
597             log.error("Error in PKCS7:", e);
598         }
599         log.debug("<getRequestDN(): " + ret);
600         return ret;
601     }
602
603     /**
604      * indicates if this message needs recipients public and private key to verify, decrypt etc. If
605      * this returns true, setKeyInfo() should be called.
606      *
607      * @return True if public and private key is needed.
608      */

609     public boolean requireKeyInfo() {
610         return true;
611     }
612
613     /**
614      * Sets the public and private key needed to decrypt/verify the message. Must be set if
615      * requireKeyInfo() returns true.
616      *
617      * @param cert certificate containing the public key.
618      * @param key private key.
619      * @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.
620      *
621      * @see #requireKeyInfo()
622      */

623     public void setKeyInfo(X509Certificate JavaDoc cert, PrivateKey JavaDoc key, String JavaDoc provider) {
624         // We don't need the public key
625
// this.cert = cert;
626
this.privateKey = key;
627         if (provider == null) {
628             this.jceProvider = "BC";
629         } else {
630             this.jceProvider = provider;
631         }
632     }
633
634     /**
635      * Returns an error number after an error has occured processing the request
636      *
637      * @return class specific error number
638      */

639     public int getErrorNo() {
640         return error;
641     }
642
643     /**
644      * Returns an error message after an error has occured processing the request
645      *
646      * @return class specific error message
647      */

648     public String JavaDoc getErrorText() {
649         return errorText;
650     }
651
652     /**
653      * Returns a senderNonce if present in the request
654      *
655      * @return senderNonce as a string of base64 encoded bytes
656      */

657     public String JavaDoc getSenderNonce() {
658         return senderNonce;
659     }
660
661     /**
662      * Returns a transaction identifier if present in the request
663      *
664      * @return transaction id
665      */

666     public String JavaDoc getTransactionId() {
667         return transactionId;
668     }
669
670     /**
671      * Returns requesters key info, key id or similar
672      *
673      * @return request key info
674      */

675     public byte[] getRequestKeyInfo() {
676         return requestKeyInfo;
677     }
678
679     /** Returns the type of SCEP message it is
680      *
681      * @return value as defined by SCEP_TYPE_PKCSREQ, SCEP_TYPE_GETCRL, SCEP_TYPE_GETCERT
682      */

683     public int getMessageType() {
684         return messageType;
685
686     }
687
688     /** @see org.ejbca.core.protocol.IRequestMessage
689      */

690     public String JavaDoc getPreferredDigestAlg() {
691         return preferredDigestAlg;
692     }
693     
694     /**
695      * Method returning the certificate used to sign the SCEP_TYPE_PKCSREQ pkcs7 request.
696      *
697      * @return The certificate used for signing or null if it doesn't exist or not been initialized.
698      */

699     public X509Certificate JavaDoc getSignerCert(){
700         return signercert;
701     }
702     
703
704     //
705
// Private helper methods
706
//
707
/* private static boolean checkKeys(PublicKey pubK, PrivateKey privK) {
708         String in = "TheTopSecretTestString";
709         byte[] text = in.getBytes();
710
711         try {
712             Cipher cipher1 = Cipher.getInstance("RSA/ECB/PKCS1PADDING", "BC");
713             cipher1.init(Cipher.ENCRYPT_MODE, pubK);
714
715             byte[] textout = cipher1.doFinal(text);
716             Cipher cipher2 = Cipher.getInstance("RSA/ECB/PKCS1PADDING", "BC");
717             cipher2.init(Cipher.DECRYPT_MODE, privK);
718
719             byte[] out = cipher2.doFinal(textout);
720             log.debug("out=" + new String(out));
721
722             return in.equals(new String(out));
723         } catch (Exception e) {
724             return false;
725         }
726     } */

727     
728 } // ScepRequestMessage
729
Popular Tags