KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ejbca > core > ejb > ca > sign > RSASignSessionBean


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.ejb.ca.sign;
15
16 import java.io.IOException JavaDoc;
17 import java.io.UnsupportedEncodingException JavaDoc;
18 import java.math.BigInteger JavaDoc;
19 import java.security.InvalidKeyException JavaDoc;
20 import java.security.NoSuchAlgorithmException JavaDoc;
21 import java.security.NoSuchProviderException JavaDoc;
22 import java.security.PublicKey JavaDoc;
23 import java.security.SecureRandom JavaDoc;
24 import java.security.cert.CRLException JavaDoc;
25 import java.security.cert.Certificate JavaDoc;
26 import java.security.cert.CertificateExpiredException JavaDoc;
27 import java.security.cert.CertificateNotYetValidException JavaDoc;
28 import java.security.cert.X509CRL JavaDoc;
29 import java.security.cert.X509Certificate JavaDoc;
30 import java.util.Arrays JavaDoc;
31 import java.util.Collection JavaDoc;
32 import java.util.Date JavaDoc;
33 import java.util.Iterator JavaDoc;
34 import java.util.Vector JavaDoc;
35
36 import javax.ejb.CreateException JavaDoc;
37 import javax.ejb.EJBException JavaDoc;
38 import javax.ejb.ObjectNotFoundException JavaDoc;
39
40 import org.ejbca.core.ejb.BaseSessionBean;
41 import org.ejbca.core.ejb.ca.auth.IAuthenticationSessionLocal;
42 import org.ejbca.core.ejb.ca.auth.IAuthenticationSessionLocalHome;
43 import org.ejbca.core.ejb.ca.caadmin.CADataLocal;
44 import org.ejbca.core.ejb.ca.caadmin.CADataLocalHome;
45 import org.ejbca.core.ejb.ca.publisher.IPublisherSessionLocal;
46 import org.ejbca.core.ejb.ca.publisher.IPublisherSessionLocalHome;
47 import org.ejbca.core.ejb.ca.store.CertificateDataBean;
48 import org.ejbca.core.ejb.ca.store.ICertificateStoreSessionLocal;
49 import org.ejbca.core.ejb.ca.store.ICertificateStoreSessionLocalHome;
50 import org.ejbca.core.ejb.log.ILogSessionLocal;
51 import org.ejbca.core.ejb.log.ILogSessionLocalHome;
52 import org.ejbca.core.model.InternalResources;
53 import org.ejbca.core.model.SecConst;
54 import org.ejbca.core.model.ca.AuthLoginException;
55 import org.ejbca.core.model.ca.AuthStatusException;
56 import org.ejbca.core.model.ca.IllegalKeyException;
57 import org.ejbca.core.model.ca.SignRequestException;
58 import org.ejbca.core.model.ca.SignRequestSignatureException;
59 import org.ejbca.core.model.ca.caadmin.CA;
60 import org.ejbca.core.model.ca.caadmin.CADoesntExistsException;
61 import org.ejbca.core.model.ca.caadmin.IllegalKeyStoreException;
62 import org.ejbca.core.model.ca.caadmin.extendedcaservices.ExtendedCAServiceNotActiveException;
63 import org.ejbca.core.model.ca.caadmin.extendedcaservices.ExtendedCAServiceRequest;
64 import org.ejbca.core.model.ca.caadmin.extendedcaservices.ExtendedCAServiceRequestException;
65 import org.ejbca.core.model.ca.caadmin.extendedcaservices.ExtendedCAServiceResponse;
66 import org.ejbca.core.model.ca.caadmin.extendedcaservices.IllegalExtendedCAServiceRequestException;
67 import org.ejbca.core.model.ca.catoken.CAToken;
68 import org.ejbca.core.model.ca.catoken.CATokenOfflineException;
69 import org.ejbca.core.model.ca.certificateprofiles.CertificateProfile;
70 import org.ejbca.core.model.ca.crl.RevokedCertInfo;
71 import org.ejbca.core.model.log.Admin;
72 import org.ejbca.core.model.log.LogEntry;
73 import org.ejbca.core.model.ra.NotFoundException;
74 import org.ejbca.core.model.ra.UserDataVO;
75 import org.ejbca.core.protocol.FailInfo;
76 import org.ejbca.core.protocol.IRequestMessage;
77 import org.ejbca.core.protocol.IResponseMessage;
78 import org.ejbca.core.protocol.ResponseStatus;
79 import org.ejbca.util.CertTools;
80 import org.ejbca.util.KeyTools;
81
82 /**
83  * Creates and signs certificates.
84  *
85  * @ejb.bean description="Session bean handling core CA function,signing certificates"
86  * display-name="RSASignSessionSB"
87  * name="RSASignSession"
88  * jndi-name="RSASignSession"
89  * local-jndi-name="SignSessionLocal"
90  * view-type="both"
91  * type="Stateless"
92  * transaction-type="Container"
93  *
94  * @ejb.transaction type="Required"
95  *
96  * @weblogic.enable-call-by-reference True
97  *
98  * @ejb.env-entry description="Name of PRNG algorithm used for random source - refer to Appendix A in the
99  * Java Cryptography Architecture API Specification And Reference for
100  * information about standard PRNG algorithm names"
101  * name="randomAlgorithm"
102  * type="java.lang.String"
103  * value="SHA1PRNG"
104  *
105  * @ejb.ejb-external-ref description="The CA entity bean"
106  * view-type="local"
107  * ref-name="ejb/CADataLocal"
108  * type="Entity"
109  * home="org.ejbca.core.ejb.ca.caadmin.CADataLocalHome"
110  * business="org.ejbca.core.ejb.ca.caadmin.CADataLocal"
111  * link="CAData"
112  *
113  * @ejb.ejb-external-ref description="The log session bean"
114  * view-type="local"
115  * ref-name="ejb/LogSessionLocal"
116  * type="Session"
117  * home="org.ejbca.core.ejb.log.ILogSessionLocalHome"
118  * business="org.ejbca.core.ejb.log.ILogSessionLocal"
119  * link="LogSession"
120  *
121  * @ejb.ejb-external-ref description="The Certificate store used to store and fetch certificates"
122  * view-type="local"
123  * ref-name="ejb/CertificateStoreSessionLocal"
124  * type="Session"
125  * home="org.ejbca.core.ejb.ca.store.ICertificateStoreSessionLocalHome"
126  * business="org.ejbca.core.ejb.ca.store.ICertificateStoreSessionLocal"
127  * link="CertificateStoreSession"
128  *
129  * @ejb.ejb-external-ref description="The Authentication session used to authenticate users when issuing certificates.
130  * Alter this to enable a custom made authentication session implementing the
131  * IAuthenticationSessionLocal interface"
132  * view-type="local"
133  * ref-name="ejb/AuthenticationSessionLocal"
134  * type="Session"
135  * home="org.ejbca.core.ejb.ca.auth.IAuthenticationSessionLocalHome"
136  * business="org.ejbca.core.ejb.ca.auth.IAuthenticationSessionLocal"
137  * link="AuthenticationSession"
138  *
139  * @ejb.ejb-external-ref description="Publishers are configured to store certificates and CRLs in additional places
140  * from the main database. Publishers runs as local beans"
141  * view-type="local"
142  * ref-name="ejb/PublisherSessionLocal"
143  * type="Session"
144  * home="org.ejbca.core.ejb.ca.publisher.IPublisherSessionLocalHome"
145  * business="org.ejbca.core.ejb.ca.publisher.IPublisherSessionLocal"
146  * link="PublisherSession"
147  *
148  * @ejb.home
149  * extends="javax.ejb.EJBHome"
150  * remote-class="org.ejbca.core.ejb.ca.sign.ISignSessionHome"
151  * local-extends="javax.ejb.EJBLocalHome"
152  * local-class="org.ejbca.core.ejb.ca.sign.ISignSessionLocalHome"
153  *
154  * @ejb.interface
155  * extends="javax.ejb.EJBObject"
156  * remote-class="org.ejbca.core.ejb.ca.sign.ISignSessionRemote"
157  * local-extends="javax.ejb.EJBLocalObject"
158  * local-class="org.ejbca.core.ejb.ca.sign.ISignSessionLocal"
159  *
160  * @version $Id: RSASignSessionBean.java,v 1.37.2.2 2007/06/05 13:36:33 anatom Exp $
161  */

162 public class RSASignSessionBean extends BaseSessionBean {
163
164
165     /**
166      * Local interfacte to ca admin store
167      */

168     private CADataLocalHome cadatahome;
169
170     /**
171      * Home interface to certificate store
172      */

173     private ICertificateStoreSessionLocalHome storeHome = null;
174
175     /* Home interface to Authentication session */
176     private IAuthenticationSessionLocalHome authHome = null;
177
178     /* Home interface to Publisher session */
179     private IPublisherSessionLocalHome publishHome = null;
180
181     /**
182      * The local interface of the log session bean
183      */

184     private ILogSessionLocal logsession;
185
186     /** Internal localization of logs and errors */
187     private static final InternalResources intres = InternalResources.getInstance();
188     
189     /**
190      * Source of good random data
191      */

192     SecureRandom JavaDoc randomSource = null;
193
194     /**
195      * Default create for SessionBean without any creation Arguments.
196      *
197      * @throws CreateException if bean instance can't be created
198      * @ejb.create-method
199      */

200     public void ejbCreate() throws CreateException JavaDoc {
201         debug(">ejbCreate()");
202
203         try {
204             // Install BouncyCastle provider
205
CertTools.installBCProvider();
206
207             // get home interfaces to other session beans used
208
storeHome = (ICertificateStoreSessionLocalHome) getLocator().getLocalHome(ICertificateStoreSessionLocalHome.COMP_NAME);
209             authHome = (IAuthenticationSessionLocalHome) getLocator().getLocalHome(IAuthenticationSessionLocalHome.COMP_NAME);
210
211             cadatahome = (CADataLocalHome) getLocator().getLocalHome(CADataLocalHome.COMP_NAME);
212
213             publishHome = (IPublisherSessionLocalHome) getLocator().getLocalHome(IPublisherSessionLocalHome.COMP_NAME);
214
215             // Get a decent source of random data
216
String JavaDoc randomAlgorithm = getLocator().getString("java:comp/env/randomAlgorithm");
217             randomSource = SecureRandom.getInstance(randomAlgorithm);
218             SernoGenerator.setAlgorithm(randomAlgorithm);
219
220
221         } catch (Exception JavaDoc e) {
222             debug("Caught exception in ejbCreate(): ", e);
223             throw new EJBException JavaDoc(e);
224         }
225
226         debug("<ejbCreate()");
227     }
228
229
230     /**
231      * Gets connection to log session bean
232      */

233     private ILogSessionLocal getLogSession() {
234         if (logsession == null) {
235             try {
236                 ILogSessionLocalHome logsessionhome = (ILogSessionLocalHome) getLocator().getLocalHome(ILogSessionLocalHome.COMP_NAME);
237                 logsession = logsessionhome.create();
238             } catch (Exception JavaDoc e) {
239                 throw new EJBException JavaDoc(e);
240             }
241         }
242         return logsession;
243     } //getLogSession
244

245
246     /**
247      * Retrieves the certificate chain for the signer. The returned certificate chain MUST have the
248      * RootCA certificate in the last position.
249      *
250      * @param admin Information about the administrator or admin preforming the event.
251      * @param caid is the issuerdn.hashCode()
252      * @return The certificate chain, never null.
253      * @ejb.permission unchecked="true"
254      * @ejb.transaction type="Supports"
255      * @ejb.interface-method view-type="both"
256      */

257     public Collection JavaDoc getCertificateChain(Admin admin, int caid) {
258         // get CA
259
CADataLocal cadata = null;
260         try {
261             cadata = cadatahome.findByPrimaryKey(new Integer JavaDoc(caid));
262         } catch (javax.ejb.FinderException JavaDoc fe) {
263             throw new EJBException JavaDoc(fe);
264         }
265
266         CA ca = null;
267         try {
268             ca = cadata.getCA();
269         } catch (java.io.UnsupportedEncodingException JavaDoc uee) {
270             throw new EJBException JavaDoc(uee);
271         } catch(IllegalKeyStoreException e){
272             throw new EJBException JavaDoc(e);
273         }
274
275         return ca.getCertificateChain();
276     } // getCertificateChain
277

278
279     /**
280      * Creates a signed PKCS7 message containing the whole certificate chain, including the
281      * provided client certificate.
282      *
283      * @param admin Information about the administrator or admin preforming the event.
284      * @param cert client certificate which we want encapsulated in a PKCS7 together with
285      * certificate chain.
286      * @return The DER-encoded PKCS7 message.
287      * @throws CADoesntExistsException if the CA does not exist or is expired, or has an invalid cert
288      * @throws SignRequestSignatureException if the certificate is not signed by the CA
289      * @ejb.interface-method view-type="both"
290      */

291     public byte[] createPKCS7(Admin admin, Certificate JavaDoc cert, boolean includeChain) throws CADoesntExistsException, SignRequestSignatureException {
292         Integer JavaDoc caid = new Integer JavaDoc(CertTools.getIssuerDN((X509Certificate JavaDoc) cert).hashCode());
293         return createPKCS7(caid.intValue(), cert, includeChain);
294     } // createPKCS7
295

296     /**
297      * Creates a signed PKCS7 message containing the whole certificate chain of the specified CA.
298      *
299      * @param admin Information about the administrator or admin preforming the event.
300      * @param caId CA for which we want a PKCS7 certificate chain.
301      * @return The DER-encoded PKCS7 message.
302      * @throws CADoesntExistsException if the CA does not exist or is expired, or has an invalid cert
303      * @ejb.interface-method view-type="both"
304      */

305     public byte[] createPKCS7(Admin admin, int caId, boolean includeChain) throws CADoesntExistsException {
306         try {
307             return createPKCS7(caId, null, includeChain);
308         } catch (SignRequestSignatureException e) {
309             String JavaDoc msg = intres.getLocalizedMessage("error.unknown");
310             error(msg, e);
311             throw new EJBException JavaDoc(e);
312         }
313     } // createPKCS7
314

315     /**
316      * Internal helper method
317      *
318      * @param admin Information about the administrator or admin preforming the event.
319      * @param caId CA for which we want a PKCS7 certificate chain.
320      * @param cert client certificate which we want ancapsulated in a PKCS7 together with
321      * certificate chain, or null
322      * @return The DER-encoded PKCS7 message.
323      * @throws CADoesntExistsException if the CA does not exist or is expired, or has an invalid cert
324      */

325     private byte[] createPKCS7(int caId, Certificate JavaDoc cert, boolean includeChain) throws CADoesntExistsException, SignRequestSignatureException {
326         debug(">createPKCS7(" + caId + ", " + CertTools.getIssuerDN((X509Certificate JavaDoc) cert) + ")");
327         byte[] returnval = null;
328         // get CA
329
CADataLocal cadata = null;
330         try {
331             cadata = cadatahome.findByPrimaryKey(new Integer JavaDoc(caId));
332         } catch (javax.ejb.FinderException JavaDoc fe) {
333             throw new CADoesntExistsException(fe);
334         }
335
336         CA ca = null;
337         try {
338             ca = cadata.getCA();
339         } catch (java.io.UnsupportedEncodingException JavaDoc uee) {
340             throw new CADoesntExistsException(uee);
341         } catch(IllegalKeyStoreException e){
342             throw new EJBException JavaDoc(e);
343         }
344
345         // Check that CA hasn't expired.
346
X509Certificate JavaDoc cacert = (X509Certificate JavaDoc) ca.getCACertificate();
347         try {
348             cacert.checkValidity();
349         } catch (CertificateExpiredException JavaDoc e) {
350             // Signers Certificate has expired.
351
cadata.setStatus(SecConst.CA_EXPIRED);
352             ca.setStatus(SecConst.CA_EXPIRED);
353             String JavaDoc msg = intres.getLocalizedMessage("signsession.caexpired", cadata.getSubjectDN());
354             throw new CADoesntExistsException(msg);
355         } catch (CertificateNotYetValidException JavaDoc cve) {
356             throw new CADoesntExistsException(cve);
357         }
358
359         returnval = ca.createPKCS7(cert, includeChain);
360         debug("<createPKCS7()");
361         return returnval;
362     } // createPKCS7
363

364     /**
365      * Requests for a certificate to be created for the passed public key with default key usage
366      * The method queries the user database for authorization of the user.
367      *
368      * @param admin Information about the administrator or admin preforming the event.
369      * @param username unique username within the instance.
370      * @param password password for the user.
371      * @param pk the public key to be put in the created certificate.
372      * @return The newly created certificate or null.
373      * @throws ObjectNotFoundException if the user does not exist.
374      * @throws AuthStatusException If the users status is incorrect.
375      * @throws AuthLoginException If the password is incorrect.
376      * @throws IllegalKeyException if the public key is of wrong type.
377      * @ejb.permission unchecked="true"
378      * @ejb.interface-method view-type="both"
379      */

380     public Certificate JavaDoc createCertificate(Admin admin, String JavaDoc username, String JavaDoc password, PublicKey JavaDoc pk) throws ObjectNotFoundException JavaDoc, AuthStatusException, AuthLoginException, IllegalKeyException, CADoesntExistsException {
381         // Default key usage is defined in certificate profiles
382
return createCertificate(admin, username, password, pk, -1);
383     } // createCertificate
384

385     /**
386      * Requests for a certificate to be created for the passed public key with the passed key
387      * usage. The method queries the user database for authorization of the user. CAs are only
388      * allowed to have certificateSign and CRLSign set.
389      *
390      * @param admin Information about the administrator or admin preforming the event.
391      * @param username unique username within the instance.
392      * @param password password for the user.
393      * @param pk the public key to be put in the created certificate.
394      * @param keyusage integer with mask describing desired key usage in format specified by
395      * X509Certificate.getKeyUsage(). id-ce-keyUsage OBJECT IDENTIFIER ::= { id-ce 15 }
396      * KeyUsage ::= BIT STRING { digitalSignature (0), nonRepudiation (1),
397      * keyEncipherment (2), dataEncipherment (3), keyAgreement (4),
398      * keyCertSign (5), cRLSign (6), encipherOnly (7),
399      * decipherOnly (8) }
400      * @return The newly created certificate or null.
401      * @throws ObjectNotFoundException if the user does not exist.
402      * @throws AuthStatusException If the users status is incorrect.
403      * @throws AuthLoginException If the password is incorrect.
404      * @throws IllegalKeyException if the public key is of wrong type.
405      * @ejb.permission unchecked="true"
406      * @ejb.interface-method view-type="both"
407      */

408     public Certificate JavaDoc createCertificate(Admin admin, String JavaDoc username, String JavaDoc password, PublicKey JavaDoc pk, boolean[] keyusage) throws ObjectNotFoundException JavaDoc, AuthStatusException, AuthLoginException, IllegalKeyException, CADoesntExistsException {
409         return createCertificate(admin, username, password, pk, CertTools.sunKeyUsageToBC(keyusage));
410     }
411
412     /**
413      * Requests for a certificate to be created for the passed public key with the passed key
414      * usage. The method queries the user database for authorization of the user. CAs are only
415      * allowed to have certificateSign and CRLSign set.
416      *
417      * @param admin Information about the administrator or admin preforming the event.
418      * @param username unique username within the instance.
419      * @param password password for the user.
420      * @param pk the public key to be put in the created certificate.
421      * @param keyusage integer with bit mask describing desired keys usage, overrides keyUsage from
422      * CertificateProfiles if allowed. Bit mask is packed in in integer using constants
423      * from CertificateData. -1 means use default keyUsage from CertificateProfile. ex. int
424      * keyusage = CertificateData.digitalSignature | CertificateData.nonRepudiation; gives
425      * digitalSignature and nonRepudiation. ex. int keyusage = CertificateData.keyCertSign
426      * | CertificateData.cRLSign; gives keyCertSign and cRLSign
427      * @return The newly created certificate or null.
428      * @throws ObjectNotFoundException if the user does not exist.
429      * @throws AuthStatusException If the users status is incorrect.
430      * @throws AuthLoginException If the password is incorrect.
431      * @throws IllegalKeyException if the public key is of wrong type.
432      * @ejb.permission unchecked="true"
433      * @ejb.interface-method view-type="both"
434      */

435     public Certificate JavaDoc createCertificate(Admin admin, String JavaDoc username, String JavaDoc password, PublicKey JavaDoc pk, int keyusage) throws ObjectNotFoundException JavaDoc, AuthStatusException, AuthLoginException, IllegalKeyException, CADoesntExistsException {
436         return createCertificate(admin, username, password, pk, keyusage, null, null, SecConst.PROFILE_NO_PROFILE, SecConst.CAID_USEUSERDEFINED);
437     }
438
439     /**
440      * Requests for a certificate to be created for the passed public key with the passed key
441      * usage. The method queries the user database for authorization of the user. CAs are only
442      * allowed to have certificateSign and CRLSign set.
443      *
444      * @param admin Information about the administrator or admin preforming the event.
445      * @param username unique username within the instance.
446      * @param password password for the user.
447      * @param pk the public key to be put in the created certificate.
448      * @param keyusage integer with bit mask describing desired keys usage, overrides keyUsage from
449      * CertificateProfiles if allowed. Bit mask is packed in in integer using constants
450      * from CertificateData. -1 means use default keyUsage from CertificateProfile. ex. int
451      * keyusage = CertificateData.digitalSignature | CertificateData.nonRepudiation; gives
452      * digitalSignature and nonRepudiation. ex. int keyusage = CertificateData.keyCertSign
453      * | CertificateData.cRLSign; gives keyCertSign and cRLSign
454      * @param notAfter an optional validity to set in the created certificate, if the profile allows validity override, null if the profiles default validity should be used.
455      * @return The newly created certificate or null.
456      * @throws ObjectNotFoundException if the user does not exist.
457      * @throws AuthStatusException If the users status is incorrect.
458      * @throws AuthLoginException If the password is incorrect.
459      * @throws IllegalKeyException if the public key is of wrong type.
460      * @ejb.permission unchecked="true"
461      * @ejb.interface-method view-type="both"
462      */

463     public Certificate JavaDoc createCertificate(Admin admin, String JavaDoc username, String JavaDoc password, PublicKey JavaDoc pk, int keyusage, Date JavaDoc notBefore, Date JavaDoc notAfter) throws ObjectNotFoundException JavaDoc, AuthStatusException, AuthLoginException, IllegalKeyException, CADoesntExistsException {
464         return createCertificate(admin, username, password, pk, keyusage, notBefore, notAfter, SecConst.PROFILE_NO_PROFILE, SecConst.CAID_USEUSERDEFINED);
465     }
466
467     /**
468      * Requests for a certificate of the specified type to be created for the passed public key.
469      * The method queries the user database for authorization of the user.
470      *
471      * @param admin Information about the administrator or admin preforming the event.
472      * @param username unique username within the instance.
473      * @param password password for the user.
474      * @param certType integer type of certificate taken from CertificateData.CERT_TYPE_XXX. the
475      * type CertificateData.CERT_TYPE_ENCRYPTION gives keyUsage keyEncipherment,
476      * dataEncipherment. the type CertificateData.CERT_TYPE_SIGNATURE gives keyUsage
477      * digitalSignature, non-repudiation. all other CERT_TYPES gives the default keyUsage
478      * digitalSignature, keyEncipherment
479      * @param pk the public key to be put in the created certificate.
480      * @return The newly created certificate or null.
481      * @throws ObjectNotFoundException if the user does not exist.
482      * @throws AuthStatusException If the users status is incorrect.
483      * @throws AuthLoginException If the password is incorrect.
484      * @throws IllegalKeyException if the public key is of wrong type.
485      * @ejb.permission unchecked="true"
486      * @ejb.interface-method view-type="both"
487      */

488     public Certificate JavaDoc createCertificate(Admin admin, String JavaDoc username, String JavaDoc password, int certType, PublicKey JavaDoc pk) throws ObjectNotFoundException JavaDoc, AuthStatusException, AuthLoginException, IllegalKeyException, CADoesntExistsException {
489         debug(">createCertificate(pk, certType)");
490         // Create an array for KeyUsage acoording to X509Certificate.getKeyUsage()
491
boolean[] keyusage = new boolean[9];
492         Arrays.fill(keyusage, false);
493         switch (certType) {
494             case CertificateDataBean.CERT_TYPE_ENCRYPTION:
495                 // keyEncipherment
496
keyusage[2] = true;
497                 // dataEncipherment
498
keyusage[3] = true;
499                 break;
500             case CertificateDataBean.CERT_TYPE_SIGNATURE:
501                 // digitalSignature
502
keyusage[0] = true;
503                 // non-repudiation
504
keyusage[1] = true;
505                 break;
506             default:
507                 // digitalSignature
508
keyusage[0] = true;
509                 // keyEncipherment
510
keyusage[2] = true;
511                 break;
512         }
513
514         Certificate JavaDoc ret = createCertificate(admin, username, password, pk, keyusage);
515         debug("<createCertificate(pk, certType)");
516         return ret;
517     } // createCertificate
518

519     /**
520      * Requests for a certificate to be created for the passed public key wrapped in a self-signed
521      * certificate. Verification of the signature (proof-of-possesion) on the request is
522      * performed, and an exception thrown if verification fails. The method queries the user
523      * database for authorization of the user.
524      *
525      * @param admin Information about the administrator or admin preforming the event.
526      * @param username unique username within the instance.
527      * @param password password for the user.
528      * @param incert a certificate containing the public key to be put in the created certificate.
529      * Other (requested) parameters in the passed certificate can be used, such as DN,
530      * Validity, KeyUsage etc. Currently only KeyUsage is considered!
531      * @return The newly created certificate or null.
532      * @throws ObjectNotFoundException if the user does not exist.
533      * @throws AuthStatusException If the users status is incorrect.
534      * @throws AuthLoginException If the password is incorrect.
535      * @throws IllegalKeyException if the public key is of wrong type.
536      * @throws SignRequestSignatureException if the provided client certificate was not signed by
537      * the CA.
538      * @ejb.permission unchecked="true"
539      * @ejb.interface-method view-type="both"
540      */

541     public Certificate JavaDoc createCertificate(Admin admin, String JavaDoc username, String JavaDoc password, Certificate JavaDoc incert) throws ObjectNotFoundException JavaDoc, AuthStatusException, AuthLoginException, IllegalKeyException, SignRequestSignatureException, CADoesntExistsException {
542         debug(">createCertificate(cert)");
543         X509Certificate JavaDoc cert = (X509Certificate JavaDoc) incert;
544         try {
545             // Convert the certificate to a BC certificate. SUN does not handle verifying RSASha256WithMGF1 for example
546
X509Certificate JavaDoc bccert = CertTools.getCertfromByteArray(incert.getEncoded());
547             bccert.verify(cert.getPublicKey());
548         } catch (Exception JavaDoc e) {
549             log.debug("Exception verify POPO: ", e);
550             String JavaDoc msg = intres.getLocalizedMessage("signsession.popverificationfailed");
551             throw new SignRequestSignatureException(msg);
552         }
553         Certificate JavaDoc ret = createCertificate(admin, username, password, cert.getPublicKey(), cert.getKeyUsage());
554         debug("<createCertificate(cert)");
555         return ret;
556     } // createCertificate
557

558     /**
559      * Requests for a certificate to be created for the passed public key wrapped in a
560      * certification request message (ex PKCS10). Verification of the signature
561      * (proof-of-possesion) on the request is performed, and an exception thrown if verification
562      * fails. The method queries the user database for authorization of the user.
563      *
564      * @param admin Information about the administrator or admin preforming the event.
565      * @param req a Certification Request message, containing the public key to be put in the
566      * created certificate. Currently no additional parameters in requests are considered!
567      * Currently no additional parameters in the PKCS10 request is considered!
568      * @param responseClass The implementation class that will be used as the response message.
569      * @return The newly created response message or null.
570      * @throws ObjectNotFoundException if the user does not exist.
571      * @throws AuthStatusException If the users status is incorrect.
572      * @throws AuthLoginException If the password is incorrect.
573      * @throws IllegalKeyException if the public key is of wrong type.
574      * @throws SignRequestException if the provided request is invalid.
575      * @throws SignRequestSignatureException if the provided client certificate was not signed by
576      * the CA.
577      * @ejb.permission unchecked="true"
578      * @ejb.interface-method view-type="both"
579      */

580     public IResponseMessage createCertificate(Admin admin, IRequestMessage req, Class JavaDoc responseClass) throws NotFoundException JavaDoc, AuthStatusException, AuthLoginException, IllegalKeyException, CADoesntExistsException, SignRequestException, SignRequestSignatureException {
581         return createCertificate(admin, req, -1, responseClass);
582     }
583
584     /**
585      * Requests for a certificate to be created for the passed public key with the passed key
586      * usage and using the given certificate profile. This method is primarily intended to be used when
587      * issueing hardtokens having multiple certificates per user.
588      * The method queries the user database for authorization of the user. CAs are only
589      * allowed to have certificateSign and CRLSign set.
590      *
591      * @param admin Information about the administrator or admin preforming the event.
592      * @param username unique username within the instance.
593      * @param password password for the user.
594      * @param pk the public key to be put in the created certificate.
595      * @param keyusage integer with bit mask describing desired keys usage, overrides keyUsage from
596      * CertificateProfiles if allowed. Bit mask is packed in in integer using constants
597      * from CertificateData. -1 means use default keyUsage from CertificateProfile. ex. int
598      * keyusage = CertificateData.digitalSignature | CertificateData.nonRepudiation; gives
599      * digitalSignature and nonRepudiation. ex. int keyusage = CertificateData.keyCertSign
600      * | CertificateData.cRLSign; gives keyCertSign and cRLSign
601      * @param certificateprofileid used to override the one set in userdata.
602      * Should be set to SecConst.PROFILE_NO_PROFILE if the usedata certificateprofileid should be used
603      * @param caid used to override the one set in userdata.�
604      * Should be set to SecConst.CAID_USEUSERDEFINED if the regular certificateprofileid should be used
605      *
606      *
607      * @return The newly created certificate or null.
608      * @throws ObjectNotFoundException if the user does not exist.
609      * @throws AuthStatusException If the users status is incorrect.
610      * @throws AuthLoginException If the password is incorrect.
611      * @throws IllegalKeyException if the public key is of wrong type.
612      *
613      * @ejb.permission unchecked="true"
614      * @ejb.interface-method view-type="both"
615      */

616     public Certificate JavaDoc createCertificate(Admin admin, String JavaDoc username, String JavaDoc password, PublicKey JavaDoc pk, int keyusage, int certificateprofileid, int caid) throws ObjectNotFoundException JavaDoc, AuthStatusException, AuthLoginException, IllegalKeyException, CADoesntExistsException {
617         return createCertificate(admin, username, password, pk, keyusage, null, null, certificateprofileid, caid);
618     }
619     
620     /**
621      * Requests for a certificate to be created for the passed public key wrapped in a
622      * certification request message (ex PKCS10). The username and password used to authorize is
623      * taken from the request message. Verification of the signature (proof-of-possesion) on the
624      * request is performed, and an exception thrown if verification fails. The method queries the
625      * user database for authorization of the user.
626      *
627      * @param admin Information about the administrator or admin preforming the event.
628      * @param req a Certification Request message, containing the public key to be put in the
629      * created certificate. Currently no additional parameters in requests are considered!
630      * @param keyUsage integer with bit mask describing desired keys usage. Bit mask is packed in
631      * in integer using contants from CertificateDataBean. ex. int keyusage =
632      * CertificateDataBean.digitalSignature | CertificateDataBean.nonRepudiation; gives
633      * digitalSignature and nonRepudiation. ex. int keyusage = CertificateDataBean.keyCertSign
634      * | CertificateDataBean.cRLSign; gives keyCertSign and cRLSign. Keyusage < 0 means that default
635      * keyUsage should be used.
636      * @param responseClass The implementation class that will be used as the response message.
637      * @return The newly created response or null.
638      * @throws ObjectNotFoundException if the user does not exist.
639      * @throws AuthStatusException If the users status is incorrect.
640      * @throws AuthLoginException If the password is incorrect.
641      * @throws IllegalKeyException if the public key is of wrong type.
642      * @throws CADoesntExistsException if the targeted CA does not exist
643      * @throws SignRequestException if the provided request is invalid.
644      * @throws SignRequestSignatureException if the provided client certificate was not signed by
645      * the CA.
646      * @ejb.permission unchecked="true"
647      * @ejb.interface-method view-type="both"
648      * @see org.ejbca.core.ejb.ca.store.CertificateDataBean
649      * @see org.ejbca.core.protocol.IRequestMessage
650      * @see org.ejbca.core.protocol.IResponseMessage
651      * @see org.ejbca.core.protocol.X509ResponseMessage
652      */

653     public IResponseMessage createCertificate(Admin admin, IRequestMessage req, int keyUsage, Class JavaDoc responseClass) throws AuthStatusException, AuthLoginException, IllegalKeyException, CADoesntExistsException, SignRequestException, SignRequestSignatureException, NotFoundException JavaDoc {
654         debug(">createCertificate(IRequestMessage)");
655         // Get CA that will receive request
656
CADataLocal cadata = null;
657         UserDataVO data = null;
658         IResponseMessage ret = null;
659         try {
660             cadata = getCAFromRequest(admin, req);
661             CA ca = cadata.getCA();
662             CAToken catoken = ca.getCAToken();
663             
664             // See if we need some key material to decrypt request
665
if (req.requireKeyInfo()) {
666                 // You go figure...scep encrypts message with the public CA-cert
667
req.setKeyInfo((X509Certificate JavaDoc)ca.getCACertificate(), catoken.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN), catoken.getProvider());
668             }
669             // Verify the request
670
if (req.verify() == false) {
671                 String JavaDoc msg = intres.getLocalizedMessage("signsession.popverificationfailed");
672                 getLogSession().log(admin, cadata.getCaId().intValue(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), req.getUsername(), null, LogEntry.EVENT_ERROR_CREATECERTIFICATE, msg);
673                 throw new SignRequestSignatureException(msg);
674             }
675             
676             if (req.getUsername() == null) {
677                 String JavaDoc msg = intres.getLocalizedMessage("signsession.nouserinrequest", req.getRequestDN());
678                 getLogSession().log(admin, cadata.getCaId().intValue(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), req.getUsername(), null, LogEntry.EVENT_ERROR_CREATECERTIFICATE, msg);
679                 throw new SignRequestException(msg);
680                 //ret.setFailInfo(FailInfo.BAD_REQUEST);
681
//ret.setStatus(ResponseStatus.FAILURE);
682
} else if (req.getPassword() == null) {
683                 String JavaDoc msg = intres.getLocalizedMessage("signsession.nopasswordinrequest");
684                 getLogSession().log(admin, cadata.getCaId().intValue(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), req.getUsername(), null, LogEntry.EVENT_ERROR_CREATECERTIFICATE, msg);
685                 throw new SignRequestException(msg);
686             } else {
687                 ResponseStatus status = ResponseStatus.SUCCESS;
688                 FailInfo failInfo = null;
689                 String JavaDoc failText = null;
690                 Certificate JavaDoc cert = null;
691                 try {
692                     // If we haven't done so yet, authenticate user
693
data = authUser(admin, req.getUsername(), req.getPassword());
694                     PublicKey JavaDoc reqpk = req.getRequestPublicKey();
695                     if (reqpk == null) {
696                         getLogSession().log(admin, cadata.getCaId().intValue(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), req.getUsername(), null, LogEntry.EVENT_ERROR_CREATECERTIFICATE, intres.getLocalizedMessage("signsession.nokeyinrequest"));
697                         throw new InvalidKeyException JavaDoc("Key is null!");
698                     }
699                     // We need to make sure we use the users registered CA here
700
if (data.getCAId() != ca.getCAId()) {
701                         failText = intres.getLocalizedMessage("signsession.wrongauthority", new Integer JavaDoc(ca.getCAId()), new Integer JavaDoc(data.getCAId()));
702                         status = ResponseStatus.FAILURE;
703                         failInfo = FailInfo.WRONG_AUTHORITY;
704                         getLogSession().log(admin, cadata.getCaId().intValue(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), req.getUsername(), null, LogEntry.EVENT_ERROR_CREATECERTIFICATE, failText);
705                     }
706
707                     if (status.equals(ResponseStatus.SUCCESS)) {
708                         Date JavaDoc notBefore = req.getRequestValidityNotBefore(); // Optionally requested validity
709
Date JavaDoc notAfter = req.getRequestValidityNotAfter(); // Optionally requested validity
710
cert = createCertificate(admin, data, ca, reqpk, keyUsage, notBefore, notAfter);
711                     }
712                 } catch (ObjectNotFoundException JavaDoc oe) {
713                     // If we didn't find the entity return error message
714
log.error("User not found: ", oe);
715                     failText = intres.getLocalizedMessage("signsession.nosuchuser", req.getUsername());
716                     status = ResponseStatus.FAILURE;
717                     failInfo = FailInfo.INCORRECT_DATA;
718                     getLogSession().log(admin, cadata.getCaId().intValue(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), req.getUsername(), null, LogEntry.EVENT_ERROR_CREATECERTIFICATE, failText);
719                 }
720                 
721                 //Create the response message with all nonces and checks etc
722
ret = req.createResponseMessage(responseClass, req, ca.getCACertificate(), catoken.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN), catoken.getPrivateKey(SecConst.CAKEYPURPOSE_KEYENCRYPT), catoken.getProvider());
723                 
724                 if ( (cert == null) && (status == ResponseStatus.SUCCESS) ) {
725                     status = ResponseStatus.FAILURE;
726                     failInfo = FailInfo.BAD_REQUEST;
727                 } else {
728                     ret.setCertificate(cert);
729                 }
730                 ret.setStatus(status);
731                 if (failInfo != null) {
732                     ret.setFailInfo(failInfo);
733                     ret.setFailText(failText);
734                 }
735             }
736             ret.create();
737             // Call authentication session and tell that we are finished with this user
738
if (ca.getFinishUser() == true) {
739                 finishUser(admin, req.getUsername(), req.getPassword());
740             }
741         } catch (NotFoundException JavaDoc oe) {
742             throw oe;
743         } catch (AuthStatusException se) {
744             throw se;
745         } catch (AuthLoginException le) {
746             throw le;
747         } catch (IllegalKeyException ke) {
748             log.error("Key is of unknown type: ", ke);
749             throw ke;
750         } catch (IllegalKeyStoreException e) {
751             throw new IllegalKeyException(e);
752         } catch (UnsupportedEncodingException JavaDoc e) {
753             throw new CADoesntExistsException(e);
754         } catch (NoSuchProviderException JavaDoc e) {
755             log.error("NoSuchProvider provider: ", e);
756         } catch (InvalidKeyException JavaDoc e) {
757             log.error("Invalid key in request: ", e);
758         } catch (NoSuchAlgorithmException JavaDoc e) {
759             log.error("No such algorithm: ", e);
760         } catch (IOException JavaDoc e) {
761             log.error("Cannot create response message: ", e);
762         } catch (CATokenOfflineException ctoe) {
763             String JavaDoc msg = intres.getLocalizedMessage("error.catokenoffline", cadata.getSubjectDN());
764             log.error(msg, ctoe);
765             getLogSession().log(admin, cadata.getCaId().intValue(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CREATECERTIFICATE, msg, ctoe);
766             throw new CADoesntExistsException(msg);
767         }
768         debug("<createCertificate(IRequestMessage)");
769         return ret;
770     }
771     
772     /**
773      * Method that generates a request failed response message. The request
774      * should already have been decrypted and verified.
775      *
776      * @param admin Information about the administrator or admin preforming the event.
777      * @param req a Certification Request message, containing the public key to be put in the
778      * created certificate. Currently no additional parameters in requests are considered!
779
780      * @param responseClass The implementation class that will be used as the response message.
781      *
782      * @return A decrypted and verified IReqeust message
783      * @throws AuthStatusException If the users status is incorrect.
784      * @throws AuthLoginException If the password is incorrect.
785      * @throws CADoesntExistsException if the targeted CA does not exist
786      * @throws SignRequestException if the provided request is invalid.
787      * @throws SignRequestSignatureException if the the request couldn't be verified.
788      * @throws IllegalKeyException
789      * @ejb.permission unchecked="true"
790      * @ejb.interface-method view-type="both"
791      * @see se.anatom.ejbca.protocol.IRequestMessage
792      * @see se.anatom.ejbca.protocol.IResponseMessage
793      * @see se.anatom.ejbca.protocol.X509ResponseMessage
794      */

795     public IResponseMessage createRequestFailedResponse(Admin admin, IRequestMessage req, Class JavaDoc responseClass) throws AuthLoginException, AuthStatusException, IllegalKeyException, CADoesntExistsException, SignRequestSignatureException, SignRequestException {
796         debug(">createRequestFailedResponse(IRequestMessage)");
797         IResponseMessage ret = null;
798         CADataLocal cadata = null;
799         try {
800             cadata = getCAFromRequest(admin, req);
801             CA ca = cadata.getCA();
802             CAToken catoken = ca.getCAToken();
803          
804             // See if we need some key material to decrypt request
805
if (req.requireKeyInfo()) {
806                 // You go figure...scep encrypts message with the public CA-cert
807
req.setKeyInfo((X509Certificate JavaDoc)ca.getCACertificate(), catoken.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN), catoken.getProvider());
808             }
809             // Verify the request
810
if (req.verify() == false) {
811                 String JavaDoc msg = intres.getLocalizedMessage("signsession.popverificationfailed");
812                 getLogSession().log(admin, cadata.getCaId().intValue(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), req.getUsername(), null, LogEntry.EVENT_ERROR_CREATECERTIFICATE, intres.getLocalizedMessage("signsession.popverificationfailed"));
813                 throw new SignRequestSignatureException(msg);
814             }
815             
816             //Create the response message with all nonces and checks etc
817
ret = req.createResponseMessage(responseClass, req, ca.getCACertificate(), catoken.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN), catoken.getPrivateKey(SecConst.CAKEYPURPOSE_KEYENCRYPT), catoken.getProvider());
818             
819             ret.setStatus(ResponseStatus.FAILURE);
820             ret.setFailInfo(FailInfo.BAD_REQUEST);
821             ret.create();
822         } catch (AuthStatusException se) {
823             throw se;
824         } catch (AuthLoginException le) {
825             throw le;
826         } catch (IllegalKeyStoreException e) {
827             throw new IllegalKeyException(e);
828         } catch (NotFoundException JavaDoc e) {
829             // This can actually not happen here?
830
throw new CADoesntExistsException(e);
831         } catch (UnsupportedEncodingException JavaDoc e) {
832             throw new CADoesntExistsException(e);
833         } catch (NoSuchProviderException JavaDoc e) {
834             log.error("NoSuchProvider provider: ", e);
835         } catch (InvalidKeyException JavaDoc e) {
836             log.error("Invalid key in request: ", e);
837         } catch (NoSuchAlgorithmException JavaDoc e) {
838             log.error("No such algorithm: ", e);
839         } catch (IOException JavaDoc e) {
840             log.error("Cannot create response message: ", e);
841         } catch (CATokenOfflineException ctoe) {
842             String JavaDoc msg = intres.getLocalizedMessage("error.catokenoffline", cadata.getSubjectDN());
843             log.error(msg, ctoe);
844             getLogSession().log(admin, cadata.getCaId().intValue(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CREATECERTIFICATE, msg, ctoe);
845             throw new CADoesntExistsException(msg);
846         }
847         debug("<createRequestFailedResponse(IRequestMessage)");
848         return ret;
849     }
850
851     /**
852      * Method that just decrypts and verifies a request and should be used in those cases
853      * a when encrypted information needs to be extracted and presented to an RA for approval.
854      *
855      * @param admin Information about the administrator or admin preforming the event.
856      * @param req a Certification Request message, containing the public key to be put in the
857      * created certificate. Currently no additional parameters in requests are considered!
858      *
859      * @return A decrypted and verified IReqeust message
860      * @throws AuthStatusException If the users status is incorrect.
861      * @throws AuthLoginException If the password is incorrect.
862      * @throws IllegalKeyException if the public key is of wrong type.
863      * @throws CADoesntExistsException if the targeted CA does not exist
864      * @throws SignRequestException if the provided request is invalid.
865      * @throws SignRequestSignatureException if the the request couldn't be verified.
866      * @ejb.permission unchecked="true"
867      * @ejb.interface-method view-type="both"
868      * @see se.anatom.ejbca.protocol.IRequestMessage
869      * @see se.anatom.ejbca.protocol.IResponseMessage
870      * @see se.anatom.ejbca.protocol.X509ResponseMessage
871      */

872     public IRequestMessage decryptAndVerifyRequest(Admin admin, IRequestMessage req) throws ObjectNotFoundException JavaDoc, AuthStatusException, AuthLoginException, IllegalKeyException, CADoesntExistsException, SignRequestException, SignRequestSignatureException {
873         debug(">decryptAndVerifyRequest(IRequestMessage)");
874         // Get CA that will receive request
875
CADataLocal cadata = null;
876             
877         try {
878             cadata = getCAFromRequest(admin, req);
879             CA ca = cadata.getCA();
880             CAToken catoken = ca.getCAToken();
881             
882             // See if we need some key material to decrypt request
883
if (req.requireKeyInfo()) {
884                 // You go figure...scep encrypts message with the public CA-cert
885
req.setKeyInfo((X509Certificate JavaDoc)ca.getCACertificate(), catoken.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN), catoken.getProvider());
886             }
887             // Verify the request
888
if (req.verify() == false) {
889                 String JavaDoc msg = intres.getLocalizedMessage("signsession.popverificationfailed");
890                 getLogSession().log(admin, cadata.getCaId().intValue(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), req.getUsername(), null, LogEntry.EVENT_ERROR_CREATECERTIFICATE, msg);
891                 throw new SignRequestSignatureException(msg);
892             }
893   
894         } catch (AuthStatusException se) {
895             throw se;
896         } catch (AuthLoginException le) {
897             throw le;
898         } catch (IllegalKeyStoreException e) {
899             throw new IllegalKeyException(e);
900         } catch (UnsupportedEncodingException JavaDoc e) {
901             throw new CADoesntExistsException(e);
902         } catch (NoSuchProviderException JavaDoc e) {
903             log.error("NoSuchProvider provider: ", e);
904         } catch (InvalidKeyException JavaDoc e) {
905             log.error("Invalid key in request: ", e);
906         } catch (NoSuchAlgorithmException JavaDoc e) {
907             log.error("No such algorithm: ", e);
908         } catch (CATokenOfflineException ctoe) {
909             String JavaDoc msg = intres.getLocalizedMessage("error.catokenoffline", cadata.getSubjectDN());
910             log.error(msg, ctoe);
911             getLogSession().log(admin, cadata.getCaId().intValue(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CREATECERTIFICATE, msg, ctoe);
912             throw new CADoesntExistsException(msg);
913         }
914         debug("<decryptAndVerifyRequest(IRequestMessage)");
915         return req;
916     }
917     
918     /**
919      * Implements ISignSession::getCRL
920      *
921      * @param admin Information about the administrator or admin preforming the event.
922      * @param req a CRL Request message
923      * @param responseClass the implementation class of the desired response
924      * @return The newly created certificate or null.
925      * @throws IllegalKeyException if the public key is of wrong type.
926      * @throws CADoesntExistsException if the targeted CA does not exist
927      * @throws SignRequestException if the provided request is invalid.
928      * @throws SignRequestSignatureException if the provided client certificate was not signed by
929      * the CA.
930      * @ejb.interface-method view-type="both"
931      */

932     public IResponseMessage getCRL(Admin admin, IRequestMessage req, Class JavaDoc responseClass) throws AuthStatusException, AuthLoginException, IllegalKeyException, CADoesntExistsException, SignRequestException, SignRequestSignatureException, UnsupportedEncodingException JavaDoc {
933         debug(">getCRL(IRequestMessage)");
934         IResponseMessage ret = null;
935         ICertificateStoreSessionLocal certificateStore = null;
936         try {
937             certificateStore = storeHome.create();
938         } catch (CreateException JavaDoc e) {
939             error("Can not create certificate store session: ", e);
940             throw new EJBException JavaDoc(e);
941         }
942         // Get CA that will receive request
943
CADataLocal cadata = getCAFromRequest(admin, req);
944         try {
945             CA ca = cadata.getCA();
946             CAToken catoken = ca.getCAToken();
947
948             if (ca.getStatus() != SecConst.CA_ACTIVE) {
949                 String JavaDoc msg = intres.getLocalizedMessage("signsession.canotactive", cadata.getSubjectDN());
950                 getLogSession().log(admin, cadata.getCaId().intValue(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_GETLASTCRL, msg);
951                 throw new EJBException JavaDoc(msg);
952             }
953
954             // Check that CA hasn't expired.
955
X509Certificate JavaDoc cacert = (X509Certificate JavaDoc) ca.getCACertificate();
956             try {
957                 cacert.checkValidity();
958             } catch (CertificateExpiredException JavaDoc cee) {
959                 // Signers Certificate has expired.
960
cadata.setStatus(SecConst.CA_EXPIRED);
961                 ca.setStatus(SecConst.CA_EXPIRED);
962                 String JavaDoc msg = intres.getLocalizedMessage("signsession.caexpired", cadata.getSubjectDN());
963                 getLogSession().log(admin, cadata.getCaId().intValue(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_GETLASTCRL, msg, cee);
964                 throw new CADoesntExistsException(msg);
965             } catch (CertificateNotYetValidException JavaDoc cve) {
966                 throw new CADoesntExistsException(cve);
967             }
968
969             // See if we need some key material to decrypt request
970
if (req.requireKeyInfo()) {
971                 // You go figure...scep encrypts message with the public CA-cert
972
req.setKeyInfo((X509Certificate JavaDoc)ca.getCACertificate(), catoken.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN), catoken.getProvider());
973             }
974             //Create the response message with all nonces and checks etc
975
ret = req.createResponseMessage(responseClass, req, ca.getCACertificate(), catoken.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN), catoken.getPrivateKey(SecConst.CAKEYPURPOSE_KEYENCRYPT), catoken.getProvider());
976             
977             // Get the CRL, don't even bother digging into the encrypted CRLIssuerDN...since we already
978
// know that we are the CA (SCEP is soooo stupid!)
979
byte[] crl = certificateStore.getLastCRL(admin, ca.getSubjectDN());
980             if (crl != null) {
981                 ret.setCrl(CertTools.getCRLfromByteArray(crl));
982                 ret.setStatus(ResponseStatus.SUCCESS);
983             } else {
984                 ret.setStatus(ResponseStatus.FAILURE);
985                 ret.setFailInfo(FailInfo.BAD_REQUEST);
986             }
987             ret.create();
988             // TODO: handle returning errors as response message,
989
// javax.ejb.ObjectNotFoundException and the others thrown...
990
} catch (NotFoundException JavaDoc e) {
991             // This actually can not happen here
992
throw new CADoesntExistsException(e);
993         } catch (IllegalKeyStoreException e) {
994             throw new IllegalKeyException(e);
995         } catch (UnsupportedEncodingException JavaDoc e) {
996             throw new CADoesntExistsException(e);
997         } catch (NoSuchProviderException JavaDoc e) {
998             log.error("NoSuchProvider provider: ", e);
999         } catch (InvalidKeyException JavaDoc e) {
1000            log.error("Invalid key in request: ", e);
1001        } catch (NoSuchAlgorithmException JavaDoc e) {
1002            log.error("No such algorithm: ", e);
1003        } catch (CRLException JavaDoc e) {
1004            log.error("Cannot create response message: ", e);
1005        } catch (IOException JavaDoc e) {
1006            log.error("Cannot create response message: ", e);
1007        } catch (CATokenOfflineException ctoe) {
1008            String JavaDoc msg = intres.getLocalizedMessage("error.catokenoffline", cadata.getSubjectDN());
1009            log.error(msg, ctoe);
1010            getLogSession().log(admin, cadata.getCaId().intValue(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_GETLASTCRL, msg, ctoe);
1011            throw new CADoesntExistsException(msg);
1012        }
1013        debug("<getCRL(IRequestMessage)");
1014        return ret;
1015    }
1016    
1017    /**
1018     * Help Method that extracts the CA specified in the request.
1019     *
1020     */

1021    private CADataLocal getCAFromRequest(Admin admin, IRequestMessage req) throws AuthStatusException, AuthLoginException, CADoesntExistsException, UnsupportedEncodingException JavaDoc{
1022        CADataLocal cadata = null;
1023        UserDataVO data = null;
1024        try {
1025            // See if we can get issuerDN directly from request
1026
if (req.getIssuerDN() != null) {
1027                String JavaDoc dn = req.getIssuerDN();
1028                debug("Got an issuerDN: "+dn);
1029                // If we have issuer and serialNo, we must find the CA certificate, to get the CAs subject name
1030
// If we don't have a serialNumber, we take a chance that it was actually the subjectDN (for example a RootCA)
1031
BigInteger JavaDoc serno = req.getSerialNo();
1032                if (serno != null) {
1033                    debug("Got a serialNumber: "+serno.toString(16));
1034                    ICertificateStoreSessionLocal certificateStore = storeHome.create();
1035                    X509Certificate JavaDoc cert = (X509Certificate JavaDoc)certificateStore.findCertificateByIssuerAndSerno(admin, dn, serno);
1036                    if (cert != null) {
1037                        dn = cert.getSubjectDN().getName();
1038                    }
1039                }
1040                debug("Using DN: "+dn);
1041                cadata = cadatahome.findByPrimaryKey(new Integer JavaDoc(dn.hashCode()));
1042                debug("Using CA (from issuerDN) with id: " + cadata.getCaId() + " and DN: " + cadata.getSubjectDN());
1043            } else if (req.getUsername() != null) {
1044                // See if we can get username and password directly from request
1045
String JavaDoc username = req.getUsername();
1046                String JavaDoc password = req.getPassword();
1047                data = authUser(admin, username, password);
1048                cadata = cadatahome.findByPrimaryKey(new Integer JavaDoc(data.getCAId()));
1049                debug("Using CA (from username) with id: " + cadata.getCaId() + " and DN: " + cadata.getSubjectDN());
1050            } else {
1051                throw new CADoesntExistsException();
1052            }
1053        } catch (javax.ejb.FinderException JavaDoc fe) {
1054            String JavaDoc msg = intres.getLocalizedMessage("signsession.canotfoundissuerusername", req.getIssuerDN(), req.getUsername());
1055            error(msg);
1056            getLogSession().log(admin, -1, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), req.getUsername(), null, LogEntry.EVENT_ERROR_CREATECERTIFICATE, msg, fe);
1057            throw new CADoesntExistsException(fe);
1058        } catch (CreateException JavaDoc ce) {
1059            // Really fatal error
1060
String JavaDoc msg = intres.getLocalizedMessage("signsession.canotfoundissuerusername", req.getIssuerDN(), req.getUsername());
1061            error(msg, ce);
1062            getLogSession().log(admin, -1, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), req.getUsername(), null, LogEntry.EVENT_ERROR_CREATECERTIFICATE, msg, ce);
1063            throw new EJBException JavaDoc(ce);
1064        }
1065        
1066        CA ca = null;
1067        try {
1068            ca = cadata.getCA();
1069            
1070            if (ca.getStatus() != SecConst.CA_ACTIVE) {
1071                String JavaDoc msg = intres.getLocalizedMessage("signsession.canotactive", cadata.getSubjectDN());
1072                getLogSession().log(admin, cadata.getCaId().intValue(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CREATECERTIFICATE, msg);
1073                throw new EJBException JavaDoc(msg);
1074            }
1075            
1076            // Check that CA hasn't expired.
1077
X509Certificate JavaDoc cacert = (X509Certificate JavaDoc) ca.getCACertificate();
1078            cacert.checkValidity();
1079        } catch (CertificateExpiredException JavaDoc cee) {
1080            // Signers Certificate has expired.
1081
cadata.setStatus(SecConst.CA_EXPIRED);
1082            ca.setStatus(SecConst.CA_EXPIRED);
1083            String JavaDoc msg = intres.getLocalizedMessage("signsession.caexpired", cadata.getSubjectDN());
1084            getLogSession().log(admin, cadata.getCaId().intValue(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CREATECERTIFICATE, msg, cee);
1085            throw new CADoesntExistsException(msg);
1086        } catch (CertificateNotYetValidException JavaDoc cve) {
1087            throw new CADoesntExistsException(cve);
1088        } catch (IllegalKeyStoreException e) {
1089            throw new EJBException JavaDoc(e);
1090        }
1091        
1092        return cadata;
1093    }
1094
1095    /**
1096     * Requests for a CRL to be created with the passed (revoked) certificates.
1097     *
1098     * @param admin Information about the administrator or admin preforming the event.
1099     * @param caid Id of the CA which CRL should be created.
1100     * @param certs vector of RevokedCertInfo object.
1101     * @return The newly created CRL in DER encoded byte form or null, use CerlTools.getCRLfromByteArray to convert to X509CRL.
1102     * @throws CATokenOfflineException
1103     * @ejb.interface-method view-type="both"
1104     */

1105    public byte[] createCRL(Admin admin, int caid, Vector JavaDoc certs) throws CATokenOfflineException {
1106        debug(">createCRL()");
1107        byte[] crlBytes;
1108        CADataLocal cadata = null;
1109        try {
1110            // get CA
1111
try {
1112                cadata = cadatahome.findByPrimaryKey(new Integer JavaDoc(caid));
1113            } catch (javax.ejb.FinderException JavaDoc fe) {
1114                String JavaDoc msg = intres.getLocalizedMessage("signsession.canotfoundcaid", new Integer JavaDoc(caid));
1115                getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CREATECRL, msg, fe);
1116                throw new EJBException JavaDoc(fe);
1117            }
1118
1119            CA ca = null;
1120            try {
1121                ca = cadata.getCA();
1122            } catch (java.io.UnsupportedEncodingException JavaDoc uee) {
1123                throw new EJBException JavaDoc(uee);
1124            }
1125            if (ca.getStatus() != SecConst.CA_ACTIVE) {
1126                String JavaDoc msg = intres.getLocalizedMessage("signsession.canotactive", cadata.getSubjectDN());
1127                getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CREATECERTIFICATE, msg);
1128                throw new CATokenOfflineException(msg);
1129            }
1130
1131            // Check that CA hasn't expired.
1132
X509Certificate JavaDoc cacert = (X509Certificate JavaDoc) ca.getCACertificate();
1133            try {
1134                cacert.checkValidity();
1135            } catch (CertificateExpiredException JavaDoc e) {
1136                // Signers Certificate has expired.
1137
cadata.setStatus(SecConst.CA_EXPIRED);
1138                ca.setStatus(SecConst.CA_EXPIRED);
1139                String JavaDoc msg = intres.getLocalizedMessage("signsession.caexpired", cadata.getSubjectDN());
1140                getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CREATECRL, msg, e);
1141                throw new EJBException JavaDoc(msg);
1142            } catch (CertificateNotYetValidException JavaDoc e) {
1143                throw new EJBException JavaDoc(e);
1144            }
1145
1146            ICertificateStoreSessionLocal certificateStore = storeHome.create();
1147            // Get number of last CRL and increase by 1
1148
int number = certificateStore.getLastCRLNumber(admin, ca.getSubjectDN()) + 1;
1149            X509CRL JavaDoc crl = null;
1150            crl = (X509CRL JavaDoc) ca.generateCRL(certs, number);
1151            String JavaDoc msg = intres.getLocalizedMessage("signsession.createdcrl", new Integer JavaDoc(number), cadata.getName(), cadata.getSubjectDN());
1152            getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_INFO_CREATECRL, msg);
1153
1154            // Store CRL in the database
1155
String JavaDoc fingerprint = CertTools.getFingerprintAsString(cacert);
1156            certificateStore.storeCRL(admin, crl.getEncoded(), fingerprint, number);
1157            // Store crl in ca CRL publishers.
1158
IPublisherSessionLocal pub = publishHome.create();
1159            pub.storeCRL(admin, ca.getCRLPublishers(), crl.getEncoded(), fingerprint, number);
1160
1161            crlBytes = crl.getEncoded();
1162        } catch (CATokenOfflineException ctoe) {
1163            String JavaDoc cadn = null;
1164            if (cadata != null) {
1165                cadn = cadata.getSubjectDN();
1166            }
1167            String JavaDoc msg = intres.getLocalizedMessage("error.catokenoffline", cadn);
1168            log.error(msg, ctoe);
1169            getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CREATECRL, msg, ctoe);
1170            throw ctoe;
1171        } catch (Exception JavaDoc e) {
1172            getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CREATECRL, intres.getLocalizedMessage("signsession.errorcreatecrl"), e);
1173            throw new EJBException JavaDoc(intres.getLocalizedMessage("signsession.errorcreatecrl"), e);
1174        }
1175        debug("<createCRL()");
1176        return crlBytes;
1177    } // createCRL
1178

1179    /**
1180     * Method that publishes the given CA certificate chain to the list of publishers.
1181     * Is mainly used by CAAdminSessionBean when CA is created.
1182     *
1183     * @param admin Information about the administrator or admin preforming the event.
1184     * @param certificatechain certchain of certificate to publish
1185     * @param usedpublishers a collection if publisher id's (Integer) indicating which publisher that should be used.
1186     * @ejb.interface-method view-type="both"
1187     */

1188    public void publishCACertificate(Admin admin, Collection JavaDoc certificatechain, Collection JavaDoc usedpublishers) {
1189        try {
1190
1191            ICertificateStoreSessionLocal certificateStore = storeHome.create();
1192
1193            Iterator JavaDoc certificates = certificatechain.iterator();
1194            while (certificates.hasNext()) {
1195                X509Certificate JavaDoc cert = (X509Certificate JavaDoc) certificates.next();
1196                String JavaDoc fingerprint = CertTools.getFingerprintAsString(cert);
1197                // Calculate the certtype
1198
boolean isSelfSigned = CertTools.isSelfSigned(cert);
1199                int type = CertificateDataBean.CERTTYPE_ENDENTITY;
1200                if (cert.getBasicConstraints() > -1) {
1201                    // this is a CA
1202
if (isSelfSigned) {
1203                        type = CertificateDataBean.CERTTYPE_ROOTCA;
1204                    } else {
1205                        type = CertificateDataBean.CERTTYPE_SUBCA;
1206                    }
1207                } else if (isSelfSigned) {
1208                    // If we don't have basic constraints, but is self signed, we are still a CA, just a stupid CA
1209
type = CertificateDataBean.CERTTYPE_ROOTCA;
1210                }
1211                
1212                String JavaDoc name = "SYSTEMCERT";
1213                if (type != CertificateDataBean.CERTTYPE_ENDENTITY) {
1214                    name = "SYSTEMCA";
1215                }
1216                // Store CA certificate in the database if it does not exist
1217
if (certificateStore.findCertificateByFingerprint(admin, fingerprint) == null) {
1218                    certificateStore.storeCertificate(admin, cert, name, fingerprint, CertificateDataBean.CERT_ACTIVE, type);
1219                }
1220                // Store cert in ca cert publishers.
1221
IPublisherSessionLocal pub = publishHome.create();
1222                if (usedpublishers != null) {
1223                    pub.storeCertificate(admin, usedpublishers, cert, fingerprint, null, fingerprint, CertificateDataBean.CERT_ACTIVE, type, -1, RevokedCertInfo.NOT_REVOKED, null);
1224                }
1225            }
1226        } catch (javax.ejb.CreateException JavaDoc ce) {
1227            throw new EJBException JavaDoc(ce);
1228        }
1229    }
1230
1231    private UserDataVO authUser(Admin admin, String JavaDoc username, String JavaDoc password) throws ObjectNotFoundException JavaDoc, AuthStatusException, AuthLoginException {
1232        // Authorize user and get DN
1233
try {
1234            IAuthenticationSessionLocal authSession = authHome.create();
1235            return authSession.authenticateUser(admin, username, password);
1236        } catch (CreateException JavaDoc e) {
1237            log.error(e);
1238            throw new EJBException JavaDoc(e);
1239        }
1240
1241    } // authUser
1242

1243    private void finishUser(Admin admin, String JavaDoc username, String JavaDoc password) {
1244        // Finnish user and set new status
1245
try {
1246            IAuthenticationSessionLocal authSession = authHome.create();
1247            authSession.finishUser(admin, username, password);
1248        } catch (CreateException JavaDoc e) {
1249            log.error(e);
1250            throw new EJBException JavaDoc(e);
1251        } catch (ObjectNotFoundException JavaDoc e) {
1252            String JavaDoc msg = intres.getLocalizedMessage("signsession.finishnouser", username);
1253            log.info(msg);
1254        }
1255    } // finishUser
1256

1257    /**
1258     * Requests for a certificate to be created for the passed public key with the passed key
1259     * usage and using the given certificate profile. This method is primarily intended to be used when
1260     * issueing hardtokens having multiple certificates per user.
1261     * The method queries the user database for authorization of the user. CAs are only
1262     * allowed to have certificateSign and CRLSign set.
1263     *
1264     * @param admin Information about the administrator or admin preforming the event.
1265     * @param username unique username within the instance.
1266     * @param password password for the user.
1267     * @param pk the public key to be put in the created certificate.
1268     * @param keyusage integer with bit mask describing desired keys usage, overrides keyUsage from
1269     * CertificateProfiles if allowed. Bit mask is packed in in integer using constants
1270     * from CertificateData. -1 means use default keyUsage from CertificateProfile. ex. int
1271     * keyusage = CertificateData.digitalSignature | CertificateData.nonRepudiation; gives
1272     * digitalSignature and nonRepudiation. ex. int keyusage = CertificateData.keyCertSign
1273     * | CertificateData.cRLSign; gives keyCertSign and cRLSign
1274     * @param notAfter an optional validity to set in the created certificate, if the profile allows validity override, null if the profiles default validity should be used.
1275     * @param certificateprofileid used to override the one set in userdata.
1276     * Should be set to SecConst.PROFILE_NO_PROFILE if the usedata certificateprofileid should be used
1277     * @param caid used to override the one set in userdata.�
1278     * Should be set to SecConst.CAID_USEUSERDEFINED if the regular certificateprofileid should be used
1279     *
1280     *
1281     * @return The newly created certificate or null.
1282     * @throws ObjectNotFoundException if the user does not exist.
1283     * @throws AuthStatusException If the users status is incorrect.
1284     * @throws AuthLoginException If the password is incorrect.
1285     * @throws IllegalKeyException if the public key is of wrong type.
1286     *
1287     */

1288    private Certificate JavaDoc createCertificate(Admin admin, String JavaDoc username, String JavaDoc password, PublicKey JavaDoc pk, int keyusage, Date JavaDoc notBefore, Date JavaDoc notAfter, int certificateprofileid, int caid) throws ObjectNotFoundException JavaDoc, AuthStatusException, AuthLoginException, IllegalKeyException, CADoesntExistsException {
1289        debug(">createCertificate(pk, ku, date)");
1290        try {
1291            // Authorize user and get DN
1292
UserDataVO data = authUser(admin, username, password);
1293            debug("Authorized user " + username + " with DN='" + data.getDN() + "'." + " with CA=" + data.getCAId());
1294            if (certificateprofileid != SecConst.PROFILE_NO_PROFILE) {
1295                debug("Overriding user certificate profile with :" + certificateprofileid);
1296                data.setCertificateProfileId(certificateprofileid);
1297            }
1298            
1299            if (caid != SecConst.CAID_USEUSERDEFINED) {
1300                debug("Overriding user caid with :" + caid);
1301                data.setCAId(caid);
1302            }
1303
1304
1305            debug("type=" + data.getType());
1306            // get CA
1307
CADataLocal cadata = null;
1308            try {
1309                cadata = cadatahome.findByPrimaryKey(new Integer JavaDoc(data.getCAId()));
1310            } catch (javax.ejb.FinderException JavaDoc fe) {
1311                String JavaDoc msg = intres.getLocalizedMessage("signsession.canotfoundcaid", new Integer JavaDoc(data.getCAId()));
1312                getLogSession().log(admin, data.getCAId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), data.getUsername(), null, LogEntry.EVENT_ERROR_CREATECERTIFICATE, msg, fe);
1313                throw new CADoesntExistsException(msg);
1314            }
1315            CA ca = null;
1316            try {
1317                ca = cadata.getCA();
1318            } catch (java.io.UnsupportedEncodingException JavaDoc uee) {
1319                throw new EJBException JavaDoc(uee);
1320            } catch(IllegalKeyStoreException e){
1321                throw new EJBException JavaDoc(e);
1322            }
1323            // Check that CA hasn't expired.
1324
X509Certificate JavaDoc cacert = (X509Certificate JavaDoc) ca.getCACertificate();
1325
1326            if (ca.getStatus() != SecConst.CA_ACTIVE) {
1327                String JavaDoc msg = intres.getLocalizedMessage("signsession.canotactive", cadata.getSubjectDN());
1328                getLogSession().log(admin, data.getCAId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CREATECERTIFICATE, msg);
1329                throw new EJBException JavaDoc(msg);
1330            }
1331
1332            try {
1333                cacert.checkValidity();
1334            } catch (CertificateExpiredException JavaDoc cee) {
1335                // Signers Certificate has expired.
1336
cadata.setStatus(SecConst.CA_EXPIRED);
1337                ca.setStatus(SecConst.CA_EXPIRED);
1338                String JavaDoc msg = intres.getLocalizedMessage("signsession.caexpired", cadata.getSubjectDN());
1339                getLogSession().log(admin, data.getCAId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CREATECERTIFICATE, msg, cee);
1340                throw new EJBException JavaDoc(msg);
1341            } catch (CertificateNotYetValidException JavaDoc cve) {
1342                throw new EJBException JavaDoc(cve);
1343            }
1344
1345
1346            // Now finally after all these checks, get the certificate
1347
Certificate JavaDoc cert = createCertificate(admin, data, ca, pk, keyusage, notBefore, notAfter);
1348            // Call authentication session and tell that we are finished with this user
1349
if (ca.getFinishUser() == true) {
1350                finishUser(admin, username, password);
1351            }
1352            debug("<createCertificate(pk, ku, date)");
1353            return cert;
1354        } catch (ObjectNotFoundException JavaDoc oe) {
1355            throw oe;
1356        } catch (AuthStatusException se) {
1357            throw se;
1358        } catch (AuthLoginException le) {
1359            throw le;
1360        } catch (IllegalKeyException ke) {
1361            throw ke;
1362        }
1363    } // createCertificate
1364

1365    /**
1366     * Creates the certificate, does NOT check any authorization on user, profiles or CA!
1367     * This must be done earlier
1368     *
1369     * @param admin administrator performing this task
1370     * @param data auth data for user to get the certificate
1371     * @param ca the CA that will sign the certificate
1372     * @param pk ther users public key to be put in the certificate
1373     * @param keyusage requested key usage for the certificate, may be ignored by the CA
1374     * @param notAfter an optional validity to set in the created certificate, if the profile allows validity override, null if the profiles default validity should be used.
1375     * @return Certificate that has been generated and signed by the CA
1376     * @throws IllegalKeyException if the public key given is invalid
1377     */

1378    private Certificate JavaDoc createCertificate(Admin admin, UserDataVO data, CA ca, PublicKey JavaDoc pk, int keyusage, Date JavaDoc notBefore, Date JavaDoc notAfter) throws IllegalKeyException {
1379        debug(">createCertificate(pk, ku, notAfter)");
1380        try {
1381            getLogSession().log(admin, data.getCAId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), data.getUsername(), null, LogEntry.EVENT_INFO_REQUESTCERTIFICATE, intres.getLocalizedMessage("signsession.requestcert", data.getUsername(), new Integer JavaDoc(data.getCAId()), new Integer JavaDoc(data.getCertificateProfileId())));
1382            // If the user is of type USER_INVALID, it cannot have any other type (in the mask)
1383
if (data.getType() == SecConst.USER_INVALID) {
1384                String JavaDoc msg = intres.getLocalizedMessage("signsession.usertypeinvalid");
1385                getLogSession().log(admin, data.getCAId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), data.getUsername(), null, LogEntry.EVENT_ERROR_CREATECERTIFICATE, msg);
1386            } else {
1387                ICertificateStoreSessionLocal certificateStore = storeHome.create();
1388                // Retrieve the certificate profile this user should have
1389
int certProfileId = data.getCertificateProfileId();
1390                CertificateProfile certProfile = certificateStore.getCertificateProfile(admin, certProfileId);
1391                // What if certProfile == null?
1392
if (certProfile == null) {
1393                    certProfileId = SecConst.CERTPROFILE_FIXED_ENDUSER;
1394                    certProfile = certificateStore.getCertificateProfile(admin, certProfileId);
1395                }
1396
1397                // Check that CAid is among available CAs
1398
boolean caauthorized = false;
1399                Iterator JavaDoc iter = certProfile.getAvailableCAs().iterator();
1400                while (iter.hasNext()) {
1401                    int next = ((Integer JavaDoc) iter.next()).intValue();
1402                    if (next == data.getCAId() || next == CertificateProfile.ANYCA) {
1403                        caauthorized = true;
1404                    }
1405                }
1406
1407                // Sign Session bean is only able to issue certificates with a end entity type certificate profile.
1408
if (certProfile.getType() != CertificateProfile.TYPE_ENDENTITY) {
1409                    String JavaDoc msg = intres.getLocalizedMessage("signsession.errorcertprofiletype", new Integer JavaDoc(certProfile.getType()));
1410                    getLogSession().log(admin, data.getCAId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), data.getUsername(), null, LogEntry.EVENT_ERROR_CREATECERTIFICATE, msg);
1411                    throw new EJBException JavaDoc(msg);
1412                }
1413
1414                if (!caauthorized) {
1415                    String JavaDoc msg = intres.getLocalizedMessage("signsession.errorcertprofilenotauthorized", new Integer JavaDoc(data.getCAId()), new Integer JavaDoc(certProfile.getType()));
1416                    getLogSession().log(admin, data.getCAId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), data.getUsername(), null, LogEntry.EVENT_ERROR_CREATECERTIFICATE, msg);
1417                    throw new EJBException JavaDoc(msg);
1418                }
1419
1420                log.debug("Using certificate profile with id " + certProfileId);
1421                int keyLength = KeyTools.getKeyLength(pk);
1422                if (keyLength == -1) {
1423                    String JavaDoc text = intres.getLocalizedMessage("signsession.unsupportedkeytype", pk.getClass().getName());
1424                    getLogSession().log(admin, data.getCAId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), data.getUsername(), null, LogEntry.EVENT_ERROR_CREATECERTIFICATE, text);
1425                    throw new IllegalKeyException(text);
1426                }
1427                log.debug("Keylength = " + keyLength);
1428                if ((keyLength < (certProfile.getMinimumAvailableBitLength() - 1))
1429                        || (keyLength > (certProfile.getMaximumAvailableBitLength()))) {
1430                    String JavaDoc text = intres.getLocalizedMessage("signsession.illegalkeylength", new Integer JavaDoc(keyLength));
1431                    getLogSession().log(admin, data.getCAId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), data.getUsername(), null, LogEntry.EVENT_ERROR_CREATECERTIFICATE, text);
1432                    log.error(text);
1433                    throw new IllegalKeyException(text);
1434                }
1435
1436                X509Certificate JavaDoc cert = (X509Certificate JavaDoc) ca.generateCertificate(data, pk, keyusage, notBefore, notAfter, certProfile);
1437
1438                getLogSession().log(admin, data.getCAId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), data.getUsername(), cert, LogEntry.EVENT_INFO_CREATECERTIFICATE, intres.getLocalizedMessage("signsession.certificateissued", data.getUsername()));
1439                if (log.isDebugEnabled()) {
1440                    debug("Generated certificate with SerialNumber '" + cert.getSerialNumber().toString(16) + "' for user '" + data.getUsername() + "'.");
1441                    debug(cert.toString());
1442                }
1443
1444                // Store certificate in the database
1445
String JavaDoc cafingerprint = null;
1446                Certificate JavaDoc cacert = ca.getCACertificate();
1447                if (cacert instanceof X509Certificate JavaDoc) {
1448                    cafingerprint = CertTools.getFingerprintAsString((X509Certificate JavaDoc)cacert);
1449                }
1450                certificateStore.storeCertificate(admin, cert, data.getUsername(), cafingerprint, CertificateDataBean.CERT_ACTIVE, certProfile.getType());
1451                // Store the request data in history table.
1452
certificateStore.addCertReqHistoryData(admin,cert,data);
1453                // Store certificate in certificate profiles publishers.
1454
IPublisherSessionLocal pub = publishHome.create();
1455                if (certProfile.getPublisherList() != null)
1456                    pub.storeCertificate(admin, certProfile.getPublisherList(), cert, data.getUsername(), data.getPassword(), cafingerprint, CertificateDataBean.CERT_ACTIVE, certProfile.getType(), -1, RevokedCertInfo.NOT_REVOKED, data.getExtendedinformation());
1457
1458                debug("<createCertificate(pk, ku, notAfter)");
1459                return cert;
1460            }
1461        } catch (IllegalKeyException ke) {
1462            throw ke;
1463        } catch (CATokenOfflineException ctoe) {
1464            String JavaDoc msg = intres.getLocalizedMessage("error.catokenoffline", ca.getSubjectDN());
1465            getLogSession().log(admin, ca.getCAId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CREATECERTIFICATE, msg, ctoe);
1466            throw new EJBException JavaDoc(msg, ctoe);
1467        } catch (Exception JavaDoc e) {
1468            log.error(e);
1469            throw new EJBException JavaDoc(e);
1470        }
1471        debug("<createCertificate(pk, ku)");
1472        log.error("Invalid user type for user " + data.getUsername());
1473        throw new EJBException JavaDoc("Invalid user type for user " + data.getUsername());
1474    } // createCertificate
1475

1476    /**
1477     * Method used to perform a extended CA Service, like OCSP CA Service.
1478     *
1479     * @param admin Information about the administrator or admin preforming the event.
1480     * @param caid the ca that should perform the service
1481     * @param request a service request.
1482     * @return A corresponding response.
1483     * @throws IllegalExtendedCAServiceRequestException
1484     * if the request was invalid.
1485     * @throws ExtendedCAServiceNotActiveException
1486     * thrown when the service for the given CA isn't activated
1487     * @throws CADoesntExistsException The given caid doesn't exists.
1488     * @ejb.interface-method view-type="both"
1489     */

1490    public ExtendedCAServiceResponse extendedService(Admin admin, int caid, ExtendedCAServiceRequest request)
1491            throws ExtendedCAServiceRequestException, IllegalExtendedCAServiceRequestException, ExtendedCAServiceNotActiveException, CADoesntExistsException {
1492
1493        // Get CA that will process request
1494
CADataLocal cadata = null;
1495        ExtendedCAServiceResponse returnval = null;
1496        try {
1497            cadata = cadatahome.findByPrimaryKey(new Integer JavaDoc(caid));
1498            if (log.isDebugEnabled()) {
1499                debug("Exteneded service with request class '"+request.getClass().getName()+"' called for CA '"+cadata.getName()+"'");
1500            }
1501            returnval = cadata.getCA().extendedService(request);
1502        } catch (javax.ejb.FinderException JavaDoc fe) {
1503            throw new CADoesntExistsException(fe);
1504        } catch (UnsupportedEncodingException JavaDoc ue) {
1505            throw new EJBException JavaDoc(ue);
1506        } catch(IllegalKeyStoreException e){
1507            throw new EJBException JavaDoc(e);
1508        }
1509
1510
1511        return returnval;
1512
1513    }
1514
1515
1516} //RSASignSessionBean
1517
Popular Tags