KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ejbca > core > ejb > ca > caadmin > CAAdminSessionBean


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.caadmin;
15
16 import java.io.ByteArrayOutputStream JavaDoc;
17 import java.io.IOException JavaDoc;
18 import java.io.UnsupportedEncodingException JavaDoc;
19 import java.security.KeyStore JavaDoc;
20 import java.security.MessageDigest JavaDoc;
21 import java.security.NoSuchAlgorithmException JavaDoc;
22 import java.security.PrivateKey JavaDoc;
23 import java.security.PublicKey JavaDoc;
24 import java.security.cert.CertPath JavaDoc;
25 import java.security.cert.CertPathValidator JavaDoc;
26 import java.security.cert.CertPathValidatorException JavaDoc;
27 import java.security.cert.CertPathValidatorResult JavaDoc;
28 import java.security.cert.Certificate JavaDoc;
29 import java.security.cert.CertificateEncodingException JavaDoc;
30 import java.security.cert.CertificateException JavaDoc;
31 import java.security.cert.CertificateExpiredException JavaDoc;
32 import java.security.cert.CertificateFactory JavaDoc;
33 import java.security.cert.CertificateNotYetValidException JavaDoc;
34 import java.security.cert.PKIXCertPathValidatorResult JavaDoc;
35 import java.security.cert.PKIXParameters JavaDoc;
36 import java.security.cert.TrustAnchor JavaDoc;
37 import java.security.cert.X509Certificate JavaDoc;
38 import java.security.interfaces.RSAPublicKey JavaDoc;
39 import java.util.ArrayList JavaDoc;
40 import java.util.Collection JavaDoc;
41 import java.util.Date JavaDoc;
42 import java.util.Enumeration JavaDoc;
43 import java.util.HashMap JavaDoc;
44 import java.util.HashSet JavaDoc;
45 import java.util.Iterator JavaDoc;
46
47 import javax.ejb.CreateException JavaDoc;
48 import javax.ejb.EJBException JavaDoc;
49 import javax.ejb.FinderException JavaDoc;
50 import javax.naming.NamingException JavaDoc;
51
52 import org.bouncycastle.asn1.ASN1Set;
53 import org.bouncycastle.jce.ECNamedCurveTable;
54 import org.bouncycastle.jce.PKCS10CertificationRequest;
55 import org.bouncycastle.jce.X509KeyUsage;
56 import org.bouncycastle.jce.interfaces.ECPrivateKey;
57 import org.bouncycastle.util.encoders.Hex;
58 import org.ejbca.core.EjbcaException;
59 import org.ejbca.core.ejb.BaseSessionBean;
60 import org.ejbca.core.ejb.ServiceLocator;
61 import org.ejbca.core.ejb.authorization.IAuthorizationSessionLocal;
62 import org.ejbca.core.ejb.authorization.IAuthorizationSessionLocalHome;
63 import org.ejbca.core.ejb.ca.crl.ICreateCRLSessionLocal;
64 import org.ejbca.core.ejb.ca.crl.ICreateCRLSessionLocalHome;
65 import org.ejbca.core.ejb.ca.sign.ISignSessionLocal;
66 import org.ejbca.core.ejb.ca.sign.ISignSessionLocalHome;
67 import org.ejbca.core.ejb.ca.store.ICertificateStoreSessionLocal;
68 import org.ejbca.core.ejb.ca.store.ICertificateStoreSessionLocalHome;
69 import org.ejbca.core.ejb.log.ILogSessionLocal;
70 import org.ejbca.core.ejb.log.ILogSessionLocalHome;
71 import org.ejbca.core.model.InternalResources;
72 import org.ejbca.core.model.SecConst;
73 import org.ejbca.core.model.authorization.AuthorizationDeniedException;
74 import org.ejbca.core.model.authorization.AvailableAccessRules;
75 import org.ejbca.core.model.ca.caadmin.CA;
76 import org.ejbca.core.model.ca.caadmin.CACacheManager;
77 import org.ejbca.core.model.ca.caadmin.CADoesntExistsException;
78 import org.ejbca.core.model.ca.caadmin.CAExistsException;
79 import org.ejbca.core.model.ca.caadmin.CAInfo;
80 import org.ejbca.core.model.ca.caadmin.IllegalKeyStoreException;
81 import org.ejbca.core.model.ca.caadmin.X509CA;
82 import org.ejbca.core.model.ca.caadmin.X509CAInfo;
83 import org.ejbca.core.model.ca.caadmin.extendedcaservices.CmsCAServiceInfo;
84 import org.ejbca.core.model.ca.caadmin.extendedcaservices.ExtendedCAServiceInfo;
85 import org.ejbca.core.model.ca.caadmin.extendedcaservices.OCSPCAServiceInfo;
86 import org.ejbca.core.model.ca.caadmin.extendedcaservices.XKMSCAServiceInfo;
87 import org.ejbca.core.model.ca.catoken.CAToken;
88 import org.ejbca.core.model.ca.catoken.CATokenAuthenticationFailedException;
89 import org.ejbca.core.model.ca.catoken.CATokenConstants;
90 import org.ejbca.core.model.ca.catoken.CATokenInfo;
91 import org.ejbca.core.model.ca.catoken.CATokenOfflineException;
92 import org.ejbca.core.model.ca.catoken.HardCATokenContainer;
93 import org.ejbca.core.model.ca.catoken.HardCATokenInfo;
94 import org.ejbca.core.model.ca.catoken.HardCATokenManager;
95 import org.ejbca.core.model.ca.catoken.IHardCAToken;
96 import org.ejbca.core.model.ca.catoken.NullCAToken;
97 import org.ejbca.core.model.ca.catoken.SoftCAToken;
98 import org.ejbca.core.model.ca.catoken.SoftCATokenInfo;
99 import org.ejbca.core.model.ca.certificateprofiles.CertificateProfile;
100 import org.ejbca.core.model.ca.crl.RevokedCertInfo;
101 import org.ejbca.core.model.log.Admin;
102 import org.ejbca.core.model.log.LogEntry;
103 import org.ejbca.core.model.ra.ExtendedInformation;
104 import org.ejbca.core.model.ra.UserDataVO;
105 import org.ejbca.core.protocol.IRequestMessage;
106 import org.ejbca.core.protocol.IResponseMessage;
107 import org.ejbca.core.protocol.PKCS10RequestMessage;
108 import org.ejbca.core.protocol.X509ResponseMessage;
109 import org.ejbca.util.Base64;
110 import org.ejbca.util.CertTools;
111 import org.ejbca.util.KeyTools;
112
113
114
115 /**
116  * Administrates and manages CAs in EJBCA system.
117  *
118  * @version $Id: CAAdminSessionBean.java,v 1.42.2.5 2007/05/21 07:31:00 jeklund Exp $
119  *
120  * @ejb.bean description="Session bean handling core CA function,signing certificates"
121  * display-name="CAAdminSB"
122  * name="CAAdminSession"
123  * jndi-name="CAAdminSession"
124  * local-jndi-name="CAAdminSessionLocal"
125  * view-type="both"
126  * type="Stateless"
127  * transaction-type="Container"
128  *
129  * @ejb.transaction type="Required"
130  *
131  * @weblogic.enable-call-by-reference True
132  *
133  * @ejb.env-entry description="Used internally to keystores in database"
134  * name="keyStorePass"
135  * type="java.lang.String"
136  * value="${ca.keystorepass}"
137  *
138  * @ejb.env-entry description="Password for OCSP keystores"
139  * name="OCSPKeyStorePass"
140  * type="java.lang.String"
141  * value="${ca.ocspkeystorepass}"
142  *
143  * @ejb.env-entry description="Password for XKMS keystores"
144  * name="XKMSKeyStorePass"
145  * type="java.lang.String"
146  * value="${ca.xkmskeystorepass}"
147  *
148  *
149  * @ejb.env-entry description="Password for CMS keystores"
150  * name="CMSKeyStorePass"
151  * type="java.lang.String"
152  * value="${ca.cmskeystorepass}"
153  *
154  * @ejb.home
155  * extends="javax.ejb.EJBHome"
156  * remote-class="org.ejbca.core.ejb.ca.caadmin.ICAAdminSessionHome"
157  * local-extends="javax.ejb.EJBLocalHome"
158  * local-class="org.ejbca.core.ejb.ca.caadmin.ICAAdminSessionLocalHome"
159  *
160  * @ejb.interface
161  * extends="javax.ejb.EJBObject"
162  * remote-class="org.ejbca.core.ejb.ca.caadmin.ICAAdminSessionRemote"
163  * local-extends="javax.ejb.EJBLocalObject"
164  * local-class="org.ejbca.core.ejb.ca.caadmin.ICAAdminSessionLocal"
165  *
166  * @ejb.ejb-external-ref description="The CA entity bean"
167  * view-type="local"
168  * ref-name="ejb/CADataLocal"
169  * type="Entity"
170  * home="org.ejbca.core.ejb.ca.caadmin.CADataLocalHome"
171  * business="org.ejbca.core.ejb.ca.caadmin.CADataLocal"
172  * link="CAData"
173  *
174  * @ejb.ejb-external-ref description="The log session bean"
175  * view-type="local"
176  * ref-name="ejb/LogSessionLocal"
177  * type="Session"
178  * home="org.ejbca.core.ejb.log.ILogSessionLocalHome"
179  * business="org.ejbca.core.ejb.log.ILogSessionLocal"
180  * link="LogSession"
181  *
182  * @ejb.ejb-external-ref description="The Authorization Session Bean"
183  * view-type="local"
184  * ref-name="ejb/AuthorizationSessionLocal"
185  * type="Session"
186  * home="org.ejbca.core.ejb.authorization.IAuthorizationSessionLocalHome"
187  * business="org.ejbca.core.ejb.authorization.IAuthorizationSessionLocal"
188  * link="AuthorizationSession"
189  *
190  * @ejb.ejb-external-ref description="The Certificate store used to store and fetch certificates"
191  * view-type="local"
192  * ref-name="ejb/CertificateStoreSessionLocal"
193  * type="Session"
194  * home="org.ejbca.core.ejb.ca.store.ICertificateStoreSessionLocalHome"
195  * business="org.ejbca.core.ejb.ca.store.ICertificateStoreSessionLocal"
196  * link="CertificateStoreSession"
197  *
198  * @ejb.ejb-external-ref description="The Sign Session Bean"
199  * view-type="local"
200  * ref-name="ejb/RSASignSessionLocal"
201  * type="Session"
202  * home="org.ejbca.core.ejb.ca.sign.ISignSessionLocalHome"
203  * business="org.ejbca.core.ejb.ca.sign.ISignSessionLocal"
204  * link="RSASignSession"
205  *
206  * @ejb.ejb-external-ref description="The CRL Create bean"
207  * view-type="local"
208  * ref-name="ejb/CreateCRLSessionLocal"
209  * type="Session"
210  * home="org.ejbca.core.ejb.ca.crl.ICreateCRLSessionLocalHome"
211  * business="org.ejbca.core.ejb.ca.crl.ICreateCRLSessionLocal"
212  * link="CreateCRLSession"
213  *
214  */

215 public class CAAdminSessionBean extends BaseSessionBean {
216
217     /** The local home interface of CAData.*/
218     private CADataLocalHome cadatahome;
219
220     /** The local interface of the log session bean */
221     private ILogSessionLocal logsession;
222
223     /** The local interface of the authorization session bean */
224     private IAuthorizationSessionLocal authorizationsession;
225
226     /** The local interface of the certificate store session bean */
227     private ICertificateStoreSessionLocal certificatestoresession;
228
229     /** The local interface of the sign session bean */
230     private ISignSessionLocal signsession;
231
232     /** The local interface of the job runner session bean used to create crls.*/
233     private ICreateCRLSessionLocal jobrunner;
234
235     /** Internal localization of logs and errors */
236     private static final InternalResources intres = InternalResources.getInstance();
237
238     /**
239      * Default create for SessionBean without any creation Arguments.
240      * @throws CreateException if bean instance can't be created
241      */

242     public void ejbCreate() throws CreateException JavaDoc {
243         cadatahome = (CADataLocalHome)getLocator().getLocalHome(CADataLocalHome.COMP_NAME);
244         // Install BouncyCastle provider
245
CertTools.installBCProvider();
246     }
247
248
249     /**
250      * Method used to create a new CA.
251      *
252      * The cainfo parameter should at least contain the following information.
253      * SubjectDN
254      * Name (if null then is subjectDN used).
255      * Validity
256      * a CATokenInfo
257      * Description (optional)
258      * Status (SecConst.CA_ACTIVE or SecConst.CA_WAITING_CERTIFICATE_RESPONSE)
259      * SignedBy (CAInfo.SELFSIGNED, CAInfo.SIGNEDBYEXTERNALCA or CAId of internal CA)
260      *
261      * For other optional values see:
262      * @see org.ejbca.core.model.ca.caadmin.CAInfo
263      * @see org.ejbca.core.model.ca.caadmin.X509CAInfo
264      *
265      * @ejb.interface-method
266      * @jboss.method-attributes transaction-timeout="900"
267      */

268     public void createCA(Admin admin, CAInfo cainfo) throws CAExistsException, AuthorizationDeniedException, CATokenOfflineException, CATokenAuthenticationFailedException {
269         int castatus = SecConst.CA_OFFLINE;
270         // Check that administrat has superadminsitrator rights.
271
try{
272             getAuthorizationSession().isAuthorizedNoLog(admin,"/super_administrator");
273         }catch(AuthorizationDeniedException ade){
274             String JavaDoc msg = intres.getLocalizedMessage("caadmin.notauthorizedtocreateca", "create", cainfo.getName());
275             getLogSession().log (admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_NOTAUTHORIZEDTORESOURCE, msg, ade);
276             throw new AuthorizationDeniedException(msg);
277         }
278         // Check that CA doesn't already exists
279
try{
280             int caid = cainfo.getCAId();
281             if(caid >=0 && caid <= CAInfo.SPECIALCAIDBORDER){
282                 String JavaDoc msg = intres.getLocalizedMessage("caadmin.wrongcaid", new Integer JavaDoc(caid));
283                 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CACREATED, msg);
284                 throw new CAExistsException(msg);
285             }
286             cadatahome.findByPrimaryKey(new Integer JavaDoc(caid));
287             String JavaDoc msg = intres.getLocalizedMessage("caadmin.caexistsid", new Integer JavaDoc(caid));
288             getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CACREATED, msg);
289             throw new CAExistsException(msg);
290         }catch(javax.ejb.FinderException JavaDoc fe) {}
291
292         try{
293             cadatahome.findByName(cainfo.getName());
294             String JavaDoc msg = intres.getLocalizedMessage("caadmin.caexistsname", cainfo.getName());
295             getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CACREATED, msg);
296             throw new CAExistsException(msg);
297         }catch(javax.ejb.FinderException JavaDoc fe) {}
298
299         // Create CAToken
300
CAToken catoken = null;
301         CATokenInfo catokeninfo = cainfo.getCATokenInfo();
302         if(catokeninfo instanceof SoftCATokenInfo){
303             try{
304                 catoken = new SoftCAToken();
305                 ((SoftCAToken) catoken).generateKeys(catokeninfo);
306             }catch(Exception JavaDoc e){
307                 String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorcreatetoken");
308                 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CACREATED, msg, e);
309                 throw new EJBException JavaDoc(e);
310             }
311         } else if(catokeninfo instanceof HardCATokenInfo){
312             catoken = new HardCATokenContainer();
313             ((HardCATokenContainer) catoken).updateCATokenInfo(catokeninfo);
314             try{
315                 catoken.activate(((HardCATokenInfo) catokeninfo).getAuthenticationCode());
316             }catch(CATokenAuthenticationFailedException ctaf){
317                 String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorcreatetokenpin");
318                 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CACREATED, msg, ctaf);
319                 throw ctaf;
320             }catch(CATokenOfflineException ctoe){
321                 String JavaDoc msg = intres.getLocalizedMessage("error.catokenoffline", cainfo.getName());
322                 getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CACREATED, msg, ctoe);
323                 throw ctoe;
324             }
325         }
326
327         // Create CA
328
CA ca = null;
329         if(cainfo instanceof X509CAInfo){
330             X509CAInfo x509cainfo = (X509CAInfo) cainfo;
331             // Create X509CA
332
ca = new X509CA((X509CAInfo) cainfo);
333             X509CA x509ca = (X509CA) ca;
334             ca.setCAToken(catoken);
335
336             // Create Certificate Chain
337
Collection JavaDoc certificatechain = null;
338
339             // getCertificateProfile
340
CertificateProfile certprofile = getCertificateStoreSession().getCertificateProfile(admin,cainfo.getCertificateProfileId());
341             if(x509cainfo.getPolicyId() != null){
342               certprofile.setUseCertificatePolicies(true);
343               certprofile.setCertificatePolicyId(x509cainfo.getPolicyId());
344             }else{
345               if(certprofile.getUseCertificatePolicies())
346                 x509ca.setPolicyId(certprofile.getCertificatePolicyId());
347             }
348
349             if(cainfo.getSignedBy() == CAInfo.SELFSIGNED){
350               try{
351                 // create selfsigned certificate
352
Certificate JavaDoc cacertificate = null;
353
354                 log.debug("CAAdminSessionBean : " + cainfo.getSubjectDN());
355
356                 UserDataVO cadata = new UserDataVO("nobody", cainfo.getSubjectDN(), cainfo.getSubjectDN().hashCode(), x509cainfo.getSubjectAltName(), null,
357                                                       0,0,0, cainfo.getCertificateProfileId(), null, null, 0, 0, null);
358                 
359                 cacertificate = ca.generateCertificate(cadata, catoken.getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN),-1, cainfo.getValidity(), certprofile);
360
361                 log.debug("CAAdminSessionBean : " + ((X509Certificate JavaDoc) cacertificate).getSubjectDN().toString());
362
363                 // Build Certificate Chain
364
certificatechain = new ArrayList JavaDoc();
365                 certificatechain.add(cacertificate);
366
367                 // set status to active
368
castatus = SecConst.CA_ACTIVE;
369               }catch(CATokenOfflineException e){
370                   String JavaDoc msg = intres.getLocalizedMessage("error.catokenoffline", cainfo.getName());
371                   getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CACREATED, msg, e);
372                   throw e;
373               }catch(Exception JavaDoc fe){
374                   String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorcreateca", cainfo.getName());
375                   getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CACREATED, msg, fe);
376                   throw new EJBException JavaDoc(fe);
377               }
378             }
379             if(cainfo.getSignedBy() == CAInfo.SIGNEDBYEXTERNALCA){
380                 certificatechain = new ArrayList JavaDoc();
381                 // set status to waiting certificate response.
382
castatus = SecConst.CA_WAITING_CERTIFICATE_RESPONSE;
383             }
384
385             if(cainfo.getSignedBy() > CAInfo.SPECIALCAIDBORDER || cainfo.getSignedBy() < 0){
386                 // Create CA signed by other internal CA.
387
try{
388                     CADataLocal signcadata = cadatahome.findByPrimaryKey(new Integer JavaDoc(cainfo.getSignedBy()));
389                     CA signca = signcadata.getCA();
390                     //Check that the signer is valid
391
checkSignerValidity(admin, signcadata);
392                     // Create cacertificate
393
Certificate JavaDoc cacertificate = null;
394
395                     UserDataVO cadata = new UserDataVO("nobody", cainfo.getSubjectDN(), cainfo.getSubjectDN().hashCode(), x509cainfo.getSubjectAltName(), null,
396                             0, 0, 0, cainfo.getCertificateProfileId(),null, null, 0, 0, null);
397                     
398                     cacertificate = signca.generateCertificate(cadata, catoken.getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN), -1, cainfo.getValidity(), certprofile);
399
400                     // Build Certificate Chain
401
Collection JavaDoc rootcachain = signca.getCertificateChain();
402                     certificatechain = new ArrayList JavaDoc();
403                     certificatechain.add(cacertificate);
404                     certificatechain.addAll(rootcachain);
405                     // set status to active
406
castatus = SecConst.CA_ACTIVE;
407                 }catch(CATokenOfflineException e){
408                     String JavaDoc msg = intres.getLocalizedMessage("error.catokenoffline", cainfo.getName());
409                     getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CACREATED, msg, e);
410                     throw e;
411                 }catch(Exception JavaDoc fe){
412                     String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorcreateca", cainfo.getName());
413                     getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CACREATED, msg, fe);
414                     throw new EJBException JavaDoc(fe);
415                 }
416             }
417
418             // Set Certificate Chain
419
x509ca.setCertificateChain(certificatechain);
420
421         }
422
423         // Publish CA certificates.
424

425         getSignSession().publishCACertificate(admin, ca.getCertificateChain(), ca.getCRLPublishers());
426         
427         
428         
429         if(castatus ==SecConst.CA_ACTIVE){
430             // activate External CA Services
431
Iterator JavaDoc iter = cainfo.getExtendedCAServiceInfos().iterator();
432             while(iter.hasNext()){
433                 ExtendedCAServiceInfo info = (ExtendedCAServiceInfo) iter.next();
434                 if(info instanceof OCSPCAServiceInfo){
435                     try{
436                         ca.initExternalService(ExtendedCAServiceInfo.TYPE_OCSPEXTENDEDSERVICE, ca);
437                         ArrayList JavaDoc ocspcertificate = new ArrayList JavaDoc();
438                         ocspcertificate.add(((OCSPCAServiceInfo) ca.getExtendedCAServiceInfo(ExtendedCAServiceInfo.TYPE_OCSPEXTENDEDSERVICE)).getOCSPSignerCertificatePath().get(0));
439                         getSignSession().publishCACertificate(admin, ocspcertificate, ca.getCRLPublishers());
440                     }catch(Exception JavaDoc fe){
441                         String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorcreatecaservice", "OCSPCAService");
442                         getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CACREATED,msg,fe);
443                         throw new EJBException JavaDoc(fe);
444                     }
445                 }
446                 if(info instanceof XKMSCAServiceInfo){
447                     try{
448                         ca.initExternalService(ExtendedCAServiceInfo.TYPE_XKMSEXTENDEDSERVICE, ca);
449                         ArrayList JavaDoc xkmscertificate = new ArrayList JavaDoc();
450                         xkmscertificate.add(((XKMSCAServiceInfo) ca.getExtendedCAServiceInfo(ExtendedCAServiceInfo.TYPE_XKMSEXTENDEDSERVICE)).getXKMSSignerCertificatePath().get(0));
451                         getSignSession().publishCACertificate(admin, xkmscertificate, ca.getCRLPublishers());
452                     }catch(Exception JavaDoc fe){
453                         String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorcreatecaservice", "XKMSCAService");
454                         getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CACREATED,msg,fe);
455                         throw new EJBException JavaDoc(fe);
456                     }
457                 }
458                 if(info instanceof CmsCAServiceInfo){
459                     try{
460                         ca.initExternalService(ExtendedCAServiceInfo.TYPE_CMSEXTENDEDSERVICE, ca);
461                         ArrayList JavaDoc cmscertificate = new ArrayList JavaDoc();
462                         cmscertificate.add(((CmsCAServiceInfo) ca.getExtendedCAServiceInfo(ExtendedCAServiceInfo.TYPE_CMSEXTENDEDSERVICE)).getCertificatePath().get(0));
463                         getSignSession().publishCACertificate(admin, cmscertificate, ca.getCRLPublishers());
464                     }catch(Exception JavaDoc fe){
465                         String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorcreatecaservice", "CMSCAService");
466                         getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CACREATED,msg,fe);
467                         throw new EJBException JavaDoc(fe);
468                     }
469                 }
470             }
471         }
472         // Store CA in database.
473
try{
474             cadatahome.create(cainfo.getSubjectDN(), cainfo.getName(), castatus, ca);
475             if(castatus == SecConst.CA_ACTIVE){
476                 // create initial CRL
477
this.getCRLCreateSession().run(admin,cainfo.getSubjectDN());
478             }
479             String JavaDoc msg = intres.getLocalizedMessage("caadmin.createdca", cainfo.getName(), new Integer JavaDoc(castatus));
480             getLogSession().log(admin, ca.getCAId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_INFO_CACREATED, msg);
481         }catch(javax.ejb.CreateException JavaDoc e){
482             String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorcreateca", cainfo.getName());
483             getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CACREATED,msg);
484             throw new EJBException JavaDoc(e);
485         }
486         
487         
488     } // createCA
489

490     /**
491      * Method used to edit the data of a CA.
492      *
493      * Not all of the CAs data can be edited after the creation, therefore will only
494      * the values from CAInfo that is possible be uppdated.
495      *
496      *
497      * For values see:
498      * @see org.ejbca.core.model.ca.caadmin.CAInfo
499      * @see org.ejbca.core.model.ca.caadmin.X509CAInfo
500      *
501      * @ejb.interface-method
502      */

503     public void editCA(Admin admin, CAInfo cainfo) throws AuthorizationDeniedException{
504         boolean ocsprenewcert = false;
505         boolean xkmsrenewcert = false;
506         boolean cmsrenewcert = false;
507
508         // Check authorization
509
try{
510             getAuthorizationSession().isAuthorizedNoLog(admin,"/super_administrator");
511         }catch(AuthorizationDeniedException e){
512             String JavaDoc msg = intres.getLocalizedMessage("caadmin.notauthorizedtoeditca", cainfo.getName());
513             getLogSession().log(admin, cainfo.getCAId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_NOTAUTHORIZEDTORESOURCE,msg,e);
514             throw new AuthorizationDeniedException(msg);
515         }
516
517         // Check if OCSP Certificate is about to be renewed.
518
Iterator JavaDoc iter = cainfo.getExtendedCAServiceInfos().iterator();
519         while(iter.hasNext()){
520           Object JavaDoc next = iter.next();
521           if(next instanceof OCSPCAServiceInfo){
522             ocsprenewcert = ((OCSPCAServiceInfo) next).getRenewFlag();
523           }
524           if(next instanceof XKMSCAServiceInfo){
525               xkmsrenewcert = ((XKMSCAServiceInfo) next).getRenewFlag();
526           }
527           if(next instanceof CmsCAServiceInfo){
528               cmsrenewcert = ((CmsCAServiceInfo) next).getRenewFlag();
529           }
530         }
531
532
533         // Get CA from database
534
try{
535             CADataLocal cadata = cadatahome.findByPrimaryKey(new Integer JavaDoc(cainfo.getCAId()));
536             CA ca = cadata.getCA();
537
538             // Update CA values
539
ca.updateCA(cainfo);
540             // Store CA in database
541
cadata.setCA(ca);
542
543             // If OCSP Certificate renew, publish the new one.
544
if(ocsprenewcert){
545               X509Certificate JavaDoc ocspcert = (X509Certificate JavaDoc) ((OCSPCAServiceInfo)
546                                          ca.getExtendedCAServiceInfo(ExtendedCAServiceInfo.TYPE_OCSPEXTENDEDSERVICE))
547                                          .getOCSPSignerCertificatePath().get(0);
548               ArrayList JavaDoc ocspcertificate = new ArrayList JavaDoc();
549               ocspcertificate.add(ocspcert);
550               getSignSession().publishCACertificate(admin, ocspcertificate, ca.getCRLPublishers());
551             }
552             if(xkmsrenewcert){
553                 X509Certificate JavaDoc xkmscert = (X509Certificate JavaDoc) ((XKMSCAServiceInfo)
554                                            ca.getExtendedCAServiceInfo(ExtendedCAServiceInfo.TYPE_XKMSEXTENDEDSERVICE))
555                                            .getXKMSSignerCertificatePath().get(0);
556               ArrayList JavaDoc xkmscertificate = new ArrayList JavaDoc();
557               xkmscertificate.add(xkmscert);
558               getSignSession().publishCACertificate(admin, xkmscertificate, ca.getCRLPublishers());
559             }
560             if(cmsrenewcert){
561                 X509Certificate JavaDoc cmscert = (X509Certificate JavaDoc) ((CmsCAServiceInfo)
562                                            ca.getExtendedCAServiceInfo(ExtendedCAServiceInfo.TYPE_CMSEXTENDEDSERVICE))
563                                            .getCertificatePath().get(0);
564               ArrayList JavaDoc cmscertificate = new ArrayList JavaDoc();
565               cmscertificate.add(cmscert);
566               getSignSession().publishCACertificate(admin, cmscertificate, ca.getCRLPublishers());
567             }
568             // Log Action
569
String JavaDoc msg = intres.getLocalizedMessage("caadmin.editedca", cainfo.getName());
570             getLogSession().log(admin, cainfo.getCAId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_INFO_CAEDITED, msg);
571         }catch(Exception JavaDoc fe) {
572             String JavaDoc msg = intres.getLocalizedMessage("caadmin.erroreditca", cainfo.getName());
573             log.error(msg, fe);
574             getLogSession().log(admin, cainfo.getCAId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEDITED, msg, fe);
575             throw new EJBException JavaDoc(fe);
576         }
577     } // editCA
578

579     /**
580      * Method used to remove a CA from the system.
581      *
582      * First there is a check that the CA isn't used by any EndEntity, Profile or AccessRule
583      * before it is removed.
584      *
585      * Should be used with care. If any certificate has been created with the CA use revokeCA instead
586      * and don't remove it.
587      *
588      * @ejb.interface-method
589      */

590     public void removeCA(Admin admin, int caid) throws AuthorizationDeniedException{
591         // check authorization
592
try{
593             getAuthorizationSession().isAuthorizedNoLog(admin,"/super_administrator");
594         }catch(AuthorizationDeniedException e){
595             String JavaDoc msg = intres.getLocalizedMessage("caadmin.notauthorizedtoremoveca", new Integer JavaDoc(caid));
596             getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_NOTAUTHORIZEDTORESOURCE, msg, e);
597             throw new AuthorizationDeniedException(msg);
598         }
599         // Get CA from database
600
try{
601             CADataLocal cadata = cadatahome.findByPrimaryKey(new Integer JavaDoc(caid));
602             // Remove CA
603
cadata.remove();
604             // Invalidate CA cache to refresh information
605
CACacheManager.instance().removeCA(caid);
606             // Remove an eventual CA token from the token registry
607
HardCATokenManager.instance().addCAToken(caid, null);
608             String JavaDoc msg = intres.getLocalizedMessage("caadmin.removedca", new Integer JavaDoc(caid));
609             getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_INFO_CAEDITED, msg);
610         }catch(Exception JavaDoc e) {
611             String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorremoveca", new Integer JavaDoc(caid));
612             log.error(msg, e);
613             getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEDITED, msg, e);
614             throw new EJBException JavaDoc(e);
615         }
616     } // removeCA
617

618     /**
619      * Renames the name of CA used in administrators web interface.
620      * This name doesn't have to be the same as SubjectDN and is only used for reference.
621      *
622      * @ejb.interface-method
623      */

624     public void renameCA(Admin admin, String JavaDoc oldname, String JavaDoc newname) throws CAExistsException, AuthorizationDeniedException{
625         // Get CA from database
626
try{
627             CADataLocal cadata = cadatahome.findByName(oldname);
628             // Check authorization
629
int caid = cadata.getCaId().intValue();
630             try{
631                 getAuthorizationSession().isAuthorizedNoLog(admin,"/super_administrator");
632             }catch(AuthorizationDeniedException e){
633                 String JavaDoc msg = intres.getLocalizedMessage("caadmin.notauthorizedtorenameca", new Integer JavaDoc(caid));
634                 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_NOTAUTHORIZEDTORESOURCE,msg,e);
635                 throw new AuthorizationDeniedException(msg);
636             }
637
638             try{
639                 CADataLocal cadatanew = cadatahome.findByName(newname);
640                 cadatanew.getCaId();
641                 throw new CAExistsException(" CA name " + newname + " already exists.");
642             }catch(javax.ejb.FinderException JavaDoc fe) {
643                 // new CA doesn't exits, it's ok to rename old one.
644
cadata.setName(newname);
645                 // Invalidate CA cache to refresh information
646
CACacheManager.instance().removeCA(cadata.getCaId().intValue());
647                 String JavaDoc msg = intres.getLocalizedMessage("caadmin.renamedca", oldname, newname);
648                 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_INFO_CAEDITED,msg);
649             }
650         }catch(javax.ejb.FinderException JavaDoc fe) {
651             String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorrenameca", oldname);
652             log.error(msg, fe);
653             getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg);
654             throw new EJBException JavaDoc(fe);
655         }
656     } // renamewCA
657

658     /**
659      * Returns a value object containing nonsensitive information about a CA give it's name.
660      * @param admin administrator calling the method
661      * @param name human readable name of CA
662      * @return value object or null if CA does not exist
663      *
664      * @ejb.transaction type="Supports"
665      * @ejb.interface-method
666      */

667     public CAInfo getCAInfo(Admin admin, String JavaDoc name) {
668         CAInfo cainfo = null;
669         try{
670             CADataLocal cadata = cadatahome.findByName(name);
671             if(cadata.getStatus() == SecConst.CA_ACTIVE && new Date JavaDoc(cadata.getExpireTime()).before(new Date JavaDoc())){
672                 cadata.setStatus(SecConst.CA_EXPIRED);
673             }
674             authorizedToCA(admin,cadata.getCaId().intValue());
675
676             cainfo = cadata.getCA().getCAInfo();
677         } catch(javax.ejb.FinderException JavaDoc fe) {
678             // ignore
679
log.debug("Can not find CA with name: '"+name+"'.");
680         } catch(Exception JavaDoc e) {
681             String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorgetcainfo", name);
682             log.error(msg, e);
683             throw new EJBException JavaDoc(e);
684         }
685         return cainfo;
686     } // getCAInfo
687

688     /**
689      * Returns a value object containing nonsensitive information about a CA give it's CAId.
690      * @param admin administrator calling the method
691      * @param caid numerical id of CA (subjectDN.hashCode())
692      * @return value object or null if CA does not exist
693      *
694      * @ejb.transaction type="Supports"
695      * @ejb.interface-method
696      */

697     public CAInfo getCAInfo(Admin admin, int caid){
698         CAInfo cainfo = null;
699         try{
700             authorizedToCA(admin,caid);
701             CADataLocal cadata = cadatahome.findByPrimaryKey(new Integer JavaDoc(caid));
702             if(cadata.getStatus() == SecConst.CA_ACTIVE && new Date JavaDoc(cadata.getExpireTime()).before(new Date JavaDoc())){
703                 cadata.setStatus(SecConst.CA_EXPIRED);
704             }
705
706             cainfo = cadata.getCA().getCAInfo();
707         } catch(javax.ejb.FinderException JavaDoc fe) {
708             // ignore
709
log.debug("Can not find CA with id: '"+caid+"'");
710         } catch(Exception JavaDoc e){
711             String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorgetcainfo", new Integer JavaDoc(caid));
712             log.error(msg, e);
713             throw new EJBException JavaDoc(e);
714         }
715         return cainfo;
716     } // getCAInfo
717

718     /**
719      * Returns a HashMap containing mappings of caid (Integer) to CA name (String) of all CAs in the system.
720      *
721      * @return HashMap with Integer->String mappings
722      * @ejb.transaction type="Supports"
723      * @ejb.interface-method
724      */

725     public HashMap JavaDoc getCAIdToNameMap(Admin admin){
726         HashMap JavaDoc returnval = new HashMap JavaDoc();
727         try{
728             Collection JavaDoc result = cadatahome.findAll();
729             Iterator JavaDoc iter = result.iterator();
730             while(iter.hasNext()){
731                 CADataLocal cadata = (CADataLocal) iter.next();
732                 returnval.put(cadata.getCaId(), cadata.getName());
733             }
734         }catch(javax.ejb.FinderException JavaDoc fe){}
735
736
737         return returnval;
738     }
739
740     /**
741      * Method returning id's of all CA's avaible to the system. i.e. not have status
742      * "external" or "waiting for certificate response"
743      *
744      * @return a Collection (Integer) of available CA id's
745      * @ejb.transaction type="Supports"
746      * @ejb.interface-method
747      */

748     public Collection JavaDoc getAvailableCAs(Admin admin){
749         ArrayList JavaDoc returnval = new ArrayList JavaDoc();
750         try{
751             Collection JavaDoc result = cadatahome.findAll();
752             Iterator JavaDoc iter = result.iterator();
753             while(iter.hasNext()){
754                 CADataLocal cadata = (CADataLocal) iter.next();
755                 if(cadata.getStatus() != SecConst.CA_WAITING_CERTIFICATE_RESPONSE && cadata.getStatus() != SecConst.CA_EXTERNAL)
756                   returnval.add(cadata.getCaId());
757             }
758         }catch(javax.ejb.FinderException JavaDoc fe){}
759
760         return returnval;
761     }
762
763
764     /**
765      * Creates a certificate request that should be sent to External Root CA for process before
766      * activation of CA.
767      *
768      * @param rootcertificates A Collection of rootcertificates.
769      * @param setstatustowaiting should be set true when creating new CAs and false for renewing old CAs
770      * @return PKCS10RequestMessage
771      *
772      * @ejb.interface-method
773      */

774     public IRequestMessage makeRequest(Admin admin, int caid, Collection JavaDoc cachain, boolean setstatustowaiting) throws CADoesntExistsException, AuthorizationDeniedException, CertPathValidatorException JavaDoc, CATokenOfflineException{
775         PKCS10RequestMessage returnval = null;
776         // Check authorization
777
try{
778             getAuthorizationSession().isAuthorizedNoLog(admin,"/super_administrator");
779         }catch(AuthorizationDeniedException e){
780             String JavaDoc msg = intres.getLocalizedMessage("caadmin.notauthorizedtocertreq", new Integer JavaDoc(caid));
781             getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_NOTAUTHORIZEDTORESOURCE,msg,e);
782             throw new AuthorizationDeniedException(msg);
783         }
784         
785         // Get CA info.
786
CADataLocal cadata = null;
787         try{
788             cadata = this.cadatahome.findByPrimaryKey(new Integer JavaDoc(caid));
789             CA ca = cadata.getCA();
790             
791             try{
792                 // if issuer is insystem CA or selfsigned, then generate new certificate.
793
if(ca.getSignedBy() == CAInfo.SIGNEDBYEXTERNALCA){
794                     
795                     
796                     ca.setRequestCertificateChain(createCertChain(cachain));
797                     
798                     // generate PKCS10CertificateRequest
799
// TODO implement PKCS10 Certificate Request attributes.
800
ASN1Set attributes = null;
801                     
802                     /* We don't use these uneccesary attributes
803                      DERConstructedSequence kName = new DERConstructedSequence();
804                      DERConstructedSet kSeq = new DERConstructedSet();
805                      kName.addObject(PKCSObjectIdentifiers.pkcs_9_at_emailAddress);
806                      kSeq.addObject(new DERIA5String("foo@bar.se"));
807                      kName.addObject(kSeq);
808                      req.setAttributes(kName);
809                      */

810                     
811                     PKCS10CertificationRequest req = new PKCS10CertificationRequest("SHA1WithRSA",
812                             CertTools.stringToBcX509Name(ca.getSubjectDN()), ca.getCAToken().getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN), attributes, ca.getCAToken().getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN), ca.getCAToken().getProvider());
813                     
814                     // create PKCS10RequestMessage
815
returnval = new PKCS10RequestMessage(req);
816                     // Set statuses.
817
if(setstatustowaiting){
818                         cadata.setStatus(SecConst.CA_WAITING_CERTIFICATE_RESPONSE);
819                         ca.setStatus(SecConst.CA_WAITING_CERTIFICATE_RESPONSE);
820                     }
821                     
822                     cadata.setCA(ca);
823                 }else{
824                     // Cannot create certificate request for internal CA
825
String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorcertreqinternalca", new Integer JavaDoc(caid));
826                     getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg);
827                     throw new EJBException JavaDoc(new EjbcaException(msg));
828                 }
829             }catch(CATokenOfflineException e) {
830                 String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorcertreq", new Integer JavaDoc(caid));
831                 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg,e);
832                 throw e;
833             }
834         }catch(CertPathValidatorException JavaDoc e) {
835             String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorcertreq", new Integer JavaDoc(caid));
836             getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg,e);
837             throw e;
838         }catch(Exception JavaDoc e){
839             String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorcertreq", new Integer JavaDoc(caid));
840             getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg,e);
841             throw new EJBException JavaDoc(e);
842         }
843         
844         String JavaDoc msg = intres.getLocalizedMessage("caadmin.certreqcreated", new Integer JavaDoc(caid));
845         getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_INFO_CAEDITED,msg);
846         
847         return returnval;
848     } // makeRequest
849

850     /**
851      * Receives a certificate response from an external CA and sets the newly created CAs status to active.
852      * @throws EjbcaException
853      *
854      * @ejb.interface-method
855      */

856     public void receiveResponse(Admin admin, int caid, IResponseMessage responsemessage) throws AuthorizationDeniedException, CertPathValidatorException JavaDoc, EjbcaException{
857         // check authorization
858
Certificate JavaDoc cacert = null;
859         // Check authorization
860
try{
861             getAuthorizationSession().isAuthorizedNoLog(admin,"/super_administrator");
862         }catch(AuthorizationDeniedException e){
863             String JavaDoc msg = intres.getLocalizedMessage("caadmin.notauthorizedtocertresp", new Integer JavaDoc(caid));
864             getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_NOTAUTHORIZEDTORESOURCE,msg,e);
865             throw new AuthorizationDeniedException(msg);
866         }
867
868         // Get CA info.
869
CADataLocal cadata = null;
870         try{
871             cadata = this.cadatahome.findByPrimaryKey(new Integer JavaDoc(caid));
872             CA ca = cadata.getCA();
873
874             try{
875                 if(responsemessage instanceof X509ResponseMessage){
876                     cacert = ((X509ResponseMessage) responsemessage).getCertificate();
877                 }else{
878                     String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorcertrespillegalmsg");
879                     getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util. Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg);
880                     throw new EjbcaException(msg);
881                 }
882
883                 // if issuer is insystem CA or selfsigned, then generate new certificate.
884
if(ca.getSignedBy() == CAInfo.SIGNEDBYEXTERNALCA){
885                     // check the validity of the certificate chain.
886

887                     // Check that DN is the equals the request.
888
if(!CertTools.getSubjectDN((X509Certificate JavaDoc) cacert).equals(CertTools.stringToBCDNString(ca.getSubjectDN()))){
889                         String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorcertrespwrongdn", CertTools.getSubjectDN((X509Certificate JavaDoc) cacert), ca.getSubjectDN());
890                         getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg);
891                         throw new EjbcaException(msg);
892                     }
893
894                     ArrayList JavaDoc cachain = new ArrayList JavaDoc();
895                     cachain.add(cacert);
896                     cachain.addAll(ca.getRequestCertificateChain());
897
898                     ca.setCertificateChain(createCertChain(cachain));
899                     // Set statuses.
900
cadata.setStatus(SecConst.CA_ACTIVE);
901
902                     // Publish CA Cert
903
ArrayList JavaDoc cacertcol = new ArrayList JavaDoc();
904                     cacertcol.add(cacert);
905                     getSignSession().publishCACertificate(admin, cacertcol, ca.getCRLPublishers());
906
907                     if(ca instanceof X509CA){
908                         cadata.setExpireTime(((X509Certificate JavaDoc) cacert).getNotAfter().getTime());
909                     }
910
911                     // activate External CA Services
912
Iterator JavaDoc iter = ca.getExternalCAServiceTypes().iterator();
913                     while(iter.hasNext()){
914                         int type = ((Integer JavaDoc) iter.next()).intValue();
915                         try{
916                             ca.initExternalService(type, ca);
917                             ArrayList JavaDoc extcacertificate = new ArrayList JavaDoc();
918                             if(type == ExtendedCAServiceInfo.TYPE_OCSPEXTENDEDSERVICE){
919                                 extcacertificate.add(((OCSPCAServiceInfo) ca.getExtendedCAServiceInfo(ExtendedCAServiceInfo.TYPE_OCSPEXTENDEDSERVICE)).getOCSPSignerCertificatePath().get(0));
920                             }
921                             if(type == ExtendedCAServiceInfo.TYPE_XKMSEXTENDEDSERVICE){
922                                 extcacertificate.add(((XKMSCAServiceInfo) ca.getExtendedCAServiceInfo(ExtendedCAServiceInfo.TYPE_XKMSEXTENDEDSERVICE)).getXKMSSignerCertificatePath().get(0));
923                             }
924                             if(type == ExtendedCAServiceInfo.TYPE_CMSEXTENDEDSERVICE){
925                                 extcacertificate.add(((CmsCAServiceInfo) ca.getExtendedCAServiceInfo(ExtendedCAServiceInfo.TYPE_CMSEXTENDEDSERVICE)).getCertificatePath().get(0));
926                             }
927                             getSignSession().publishCACertificate(admin, extcacertificate, ca.getCRLPublishers());
928                         }catch(CATokenOfflineException e){
929                             String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorcreatecaservice", new Integer JavaDoc(caid));
930                             getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CACREATED,msg,e);
931                             throw e;
932                         }catch(Exception JavaDoc fe){
933                             String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorcreatecaservice", new Integer JavaDoc(caid));
934                             getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CACREATED,msg,fe);
935                             throw new EJBException JavaDoc(fe);
936                         }
937                     }
938                     // Save CA
939
cadata.setCA(ca);
940                     // create initial CRL
941
this.getCRLCreateSession().run(admin,ca.getSubjectDN());
942                 }else{
943                     String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorcreatecaservice", new Integer JavaDoc(caid));
944                     // Cannot create certificate request for internal CA
945
getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg);
946                     throw new EjbcaException(msg);
947                 }
948
949             }catch(CATokenOfflineException e){
950                 String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorcertresp", new Integer JavaDoc(caid));
951                 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg, e);
952                 throw e;
953             } catch (CertificateEncodingException JavaDoc e) {
954                 String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorcertresp", new Integer JavaDoc(caid));
955                 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg, e);
956                 throw new EjbcaException(e.getMessage());
957             } catch (CertificateException JavaDoc e) {
958                 String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorcertresp", new Integer JavaDoc(caid));
959                 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg, e);
960                 throw new EjbcaException(e.getMessage());
961             } catch (IOException JavaDoc e) {
962                 String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorcertresp", new Integer JavaDoc(caid));
963                 getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg, e);
964                 throw new EjbcaException(e.getMessage());
965             }
966         }catch(FinderException JavaDoc e){
967             String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorcertresp", new Integer JavaDoc(caid));
968             getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg, e);
969             throw new EjbcaException(e.getMessage());
970         } catch (UnsupportedEncodingException JavaDoc e) {
971             String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorcertresp", new Integer JavaDoc(caid));
972             getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg, e);
973             throw new EjbcaException(e.getMessage());
974         }
975
976         String JavaDoc msg = intres.getLocalizedMessage("caadmin.certrespreceived", new Integer JavaDoc(caid));
977         getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_INFO_CAEDITED,msg);
978     } // recieveResponse
979

980     /**
981      * Processes a Certificate Request from an external CA.
982      *
983      * @ejb.interface-method
984      */

985     public IResponseMessage processRequest(Admin admin, CAInfo cainfo, IRequestMessage requestmessage)
986     throws CAExistsException, CADoesntExistsException, AuthorizationDeniedException, CATokenOfflineException {
987         CA ca = null;
988         Collection JavaDoc certchain = null;
989         IResponseMessage returnval = null;
990         // check authorization
991
try{
992             getAuthorizationSession().isAuthorizedNoLog(admin,"/super_administrator");
993         }catch(AuthorizationDeniedException e){
994             String JavaDoc msg = intres.getLocalizedMessage("caadmin.notauthorizedtocertresp", cainfo.getName());
995             getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_NOTAUTHORIZEDTORESOURCE,msg,e);
996             throw new AuthorizationDeniedException(msg);
997         }
998
999         // Check that CA doesn't already exists
1000
try{
1001            int caid = cainfo.getCAId();
1002            if(caid >=0 && caid <= CAInfo.SPECIALCAIDBORDER){
1003                String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorcaexists", cainfo.getName());
1004                getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg);
1005                throw new CAExistsException(msg);
1006            }
1007            cadatahome.findByPrimaryKey(new Integer JavaDoc(caid));
1008            String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorcaexists", cainfo.getName());
1009            getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg);
1010            throw new CAExistsException(msg);
1011        }catch(javax.ejb.FinderException JavaDoc fe) {}
1012
1013        try{
1014            cadatahome.findByName(cainfo.getName());
1015            String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorcaexists", cainfo.getName());
1016            getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg);
1017            throw new CAExistsException(msg);
1018        }catch(javax.ejb.FinderException JavaDoc fe) {}
1019
1020        //get signing CA
1021
if(cainfo.getSignedBy() > CAInfo.SPECIALCAIDBORDER || cainfo.getSignedBy() < 0){
1022            try{
1023                CADataLocal signcadata = cadatahome.findByPrimaryKey(new Integer JavaDoc(cainfo.getSignedBy()));
1024                CA signca = signcadata.getCA();
1025                try{
1026                    //Check that the signer is valid
1027
checkSignerValidity(admin, signcadata);
1028
1029                    // Get public key from request
1030
PublicKey JavaDoc publickey = requestmessage.getRequestPublicKey();
1031
1032                    // Create cacertificate
1033
Certificate JavaDoc cacertificate = null;
1034                    if(cainfo instanceof X509CAInfo){
1035                        UserDataVO cadata = new UserDataVO("nobody", cainfo.getSubjectDN(), cainfo.getSubjectDN().hashCode(), ((X509CAInfo) cainfo).getSubjectAltName(), null,
1036                                0, 0, 0, cainfo.getCertificateProfileId(), null, null, 0, 0, null);
1037                        if(requestmessage instanceof PKCS10RequestMessage){
1038                          ExtendedInformation extInfo = new ExtendedInformation();
1039                          PKCS10CertificationRequest pkcs10 = ((PKCS10RequestMessage) requestmessage).getCertificationRequest();
1040                          extInfo.setCustomData("PKCS10", new String JavaDoc(Base64.encode(pkcs10.getEncoded())));
1041                          cadata.setExtendedinformation(extInfo);
1042                        }
1043                        CertificateProfile certprofile = getCertificateStoreSession().getCertificateProfile(admin, cainfo.getCertificateProfileId());
1044                        cacertificate = signca.generateCertificate(cadata, publickey, -1, cainfo.getValidity(), certprofile);
1045                        returnval = new X509ResponseMessage();
1046                        returnval.setCertificate(cacertificate);
1047                    }
1048                    // Build Certificate Chain
1049
Collection JavaDoc rootcachain = signca.getCertificateChain();
1050                    certchain = new ArrayList JavaDoc();
1051                    certchain.add(cacertificate);
1052                    certchain.addAll(rootcachain);
1053
1054                    if(cainfo instanceof X509CAInfo){
1055                        // Create X509CA
1056
ca = new X509CA((X509CAInfo) cainfo);
1057                        ca.setCertificateChain(certchain);
1058                        ca.setCAToken(new NullCAToken());
1059                    }
1060
1061                    // set status to active
1062
cadatahome.create(cainfo.getSubjectDN(), cainfo.getName(), SecConst.CA_EXTERNAL, ca);
1063
1064                    // Publish CA certificates.
1065
getSignSession().publishCACertificate(admin, ca.getCertificateChain(), ca.getCRLPublishers());
1066
1067                }catch(CATokenOfflineException e){
1068                    String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorprocess", cainfo.getName());
1069                    getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg,e);
1070                    throw e;
1071                }
1072            }catch(Exception JavaDoc e){
1073                String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorprocess", cainfo.getName());
1074                getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg,e);
1075                throw new EJBException JavaDoc(e);
1076            }
1077
1078        }
1079
1080        if(certchain != null) {
1081            String JavaDoc msg = intres.getLocalizedMessage("caadmin.processedca", cainfo.getName());
1082            getLogSession().log(admin, cainfo.getCAId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_INFO_CAEDITED,msg);
1083        }
1084        else {
1085            String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorprocess", cainfo.getName());
1086            getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg);
1087        }
1088
1089        return returnval;
1090    } // processRequest
1091

1092    /**
1093     * Renews a existing CA certificate using the same keys as before. Data about new CA is taken
1094     * from database.
1095     *
1096     * @param certificateresponce should be set with new certificatechain if CA is signed by external
1097     * RootCA, otherwise use the null value.
1098     * @param regenerateKeys, if true and the CA have a softCAToken the keys are regenerated before the certrequest.
1099     *
1100     * @ejb.interface-method
1101     */

1102    public void renewCA(Admin admin, int caid, IResponseMessage responsemessage, boolean regenerateKeys) throws CADoesntExistsException, AuthorizationDeniedException, CertPathValidatorException JavaDoc, CATokenOfflineException{
1103        debug(">CAAdminSession, renewCA(), caid=" + caid);
1104        Collection JavaDoc cachain = null;
1105        Certificate JavaDoc cacertificate = null;
1106        // check authorization
1107
try{
1108            getAuthorizationSession().isAuthorizedNoLog(admin,"/super_administrator");
1109        }catch(AuthorizationDeniedException e){
1110            String JavaDoc msg = intres.getLocalizedMessage("caadmin.notauthorizedtorenew", new Integer JavaDoc(caid));
1111            getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_NOTAUTHORIZEDTORESOURCE,msg,e);
1112            throw new AuthorizationDeniedException(msg);
1113        }
1114
1115        // Get CA info.
1116
CADataLocal cadata = null;
1117        try{
1118            cadata = this.cadatahome.findByPrimaryKey(new Integer JavaDoc(caid));
1119            CA ca = cadata.getCA();
1120            
1121            
1122            if(ca.getStatus() == SecConst.CA_OFFLINE){
1123                String JavaDoc msg = intres.getLocalizedMessage("error.catokenoffline", cadata.getName());
1124                throw new CATokenOfflineException(msg);
1125            }
1126            
1127            CAToken caToken = ca.getCAToken();
1128            if(caToken instanceof SoftCAToken && regenerateKeys){
1129                ((SoftCAToken) caToken).generateKeys(ca.getCAToken().getCATokenInfo());
1130                ca.setCAToken(caToken);
1131            }
1132            
1133            try{
1134                // if issuer is insystem CA or selfsigned, then generate new certificate.
1135
if(ca.getSignedBy() != CAInfo.SIGNEDBYEXTERNALCA){
1136                    if(ca.getSignedBy() == CAInfo.SELFSIGNED){
1137                        // create selfsigned certificate
1138
if( ca instanceof X509CA){
1139                            UserDataVO cainfodata = new UserDataVO("nobody", ca.getSubjectDN(), ca.getSubjectDN().hashCode(), ((X509CA) ca).getSubjectAltName(), null,
1140                                    0, 0, 0, ca.getCertificateProfileId(), null, null, 0, 0 ,null);
1141
1142                            CertificateProfile certprofile = getCertificateStoreSession().getCertificateProfile(admin, ca.getCertificateProfileId());
1143                            cacertificate = ca.generateCertificate(cainfodata, ca.getCAToken().getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN),-1, ca.getValidity(), certprofile);
1144                        }
1145                        // Build Certificate Chain
1146
cachain = new ArrayList JavaDoc();
1147                        cachain.add(cacertificate);
1148
1149                    }else{
1150                        // Resign with CA above.
1151
if(ca.getSignedBy() > CAInfo.SPECIALCAIDBORDER || ca.getSignedBy() < 0){
1152                            // Create CA signed by other internal CA.
1153
CADataLocal signcadata = cadatahome.findByPrimaryKey(new Integer JavaDoc(ca.getSignedBy()));
1154                            CA signca = signcadata.getCA();
1155                            //Check that the signer is valid
1156
checkSignerValidity(admin, signcadata);
1157                            // Create cacertificate
1158
if( ca instanceof X509CA){
1159                                UserDataVO cainfodata = new UserDataVO("nobody", ca.getSubjectDN(), ca.getSubjectDN().hashCode(), ((X509CA) ca).getSubjectAltName(), null,
1160                                        0,0,0, ca.getCertificateProfileId(), null, null, 0,0, null);
1161
1162                                CertificateProfile certprofile = getCertificateStoreSession().getCertificateProfile(admin, ca.getCertificateProfileId());
1163                                cacertificate = signca.generateCertificate(cainfodata, ca.getCAToken().getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN),-1, ca.getValidity(), certprofile);
1164                            }
1165
1166                            // Build Certificate Chain
1167
Collection JavaDoc rootcachain = signca.getCertificateChain();
1168                            cachain = new ArrayList JavaDoc();
1169                            cachain.add(cacertificate);
1170                            cachain.addAll(rootcachain);
1171                        }
1172                    }
1173                }else{
1174                    // if external signer then use signed certificate.
1175
// check the validity of the certificate chain.
1176
if(responsemessage instanceof X509ResponseMessage){
1177                        cacertificate = ((X509ResponseMessage) responsemessage).getCertificate();
1178                    }else{
1179                        String JavaDoc msg = intres.getLocalizedMessage("error.errorcertrespillegalmsg");
1180                        getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg);
1181                        throw new EJBException JavaDoc(new EjbcaException(msg));
1182                    }
1183
1184                    // Check that DN is the equals the request.
1185
if(!CertTools.getSubjectDN((X509Certificate JavaDoc) cacertificate).equals(CertTools.stringToBCDNString(ca.getSubjectDN()))){
1186                        String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorcertrespwrongdn", CertTools.getSubjectDN((X509Certificate JavaDoc) cacertificate), ca.getSubjectDN());
1187                        getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg);
1188                        throw new EJBException JavaDoc(new EjbcaException(msg));
1189                    }
1190
1191                    cachain = new ArrayList JavaDoc();
1192                    cachain.add(cacertificate);
1193                    cachain.addAll(ca.getRequestCertificateChain());
1194
1195                    cachain = createCertChain(cachain);
1196
1197                }
1198                // Set statuses.
1199
if(cacertificate instanceof X509Certificate JavaDoc)
1200                    cadata.setExpireTime(((X509Certificate JavaDoc) cacertificate).getNotAfter().getTime());
1201                cadata.setStatus(SecConst.CA_ACTIVE);
1202
1203                ca.setCertificateChain(cachain);
1204                cadata.setCA(ca);
1205
1206                // Publish the new CA certificate
1207
ArrayList JavaDoc cacert = new ArrayList JavaDoc();
1208                 cacert.add(ca.getCACertificate());
1209                 getSignSession().publishCACertificate(admin, cacert, ca.getCRLPublishers());
1210
1211
1212            }catch(CATokenOfflineException e){
1213                String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorrenewca", new Integer JavaDoc(caid));
1214                getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg,e);
1215                throw e;
1216            }
1217        }catch(Exception JavaDoc e){
1218            String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorrenewca", new Integer JavaDoc(caid));
1219            getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg,e);
1220            throw new EJBException JavaDoc(e);
1221        }
1222        String JavaDoc msg = intres.getLocalizedMessage("caadmin.renewdca", new Integer JavaDoc(caid));
1223        getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_INFO_CARENEWED,msg);
1224        debug("<CAAdminSession, renewCA(), caid=" + caid);
1225    } // renewCA
1226

1227    /**
1228     * Method that revokes the CA. After this is all certificates created by this CA
1229     * revoked and a final CRL is created.
1230     *
1231     * @param reason one of RevokedCertInfo.REVOKATION_REASON values.
1232     *
1233     * @ejb.interface-method
1234     */

1235    public void revokeCA(Admin admin, int caid, int reason) throws CADoesntExistsException, AuthorizationDeniedException{
1236        // check authorization
1237
try{
1238            getAuthorizationSession().isAuthorizedNoLog(admin,"/super_administrator");
1239        }catch(AuthorizationDeniedException e){
1240            String JavaDoc msg = intres.getLocalizedMessage("caadmin.notauthorizedtorevoke", new Integer JavaDoc(caid));
1241            getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_NOTAUTHORIZEDTORESOURCE,msg,e);
1242            throw new AuthorizationDeniedException(msg);
1243        }
1244
1245        // Get CA info.
1246
CADataLocal ca = null;
1247        try{
1248            ca = this.cadatahome.findByPrimaryKey(new Integer JavaDoc(caid));
1249        }catch(javax.ejb.FinderException JavaDoc fe){
1250           throw new EJBException JavaDoc(fe);
1251        }
1252
1253        String JavaDoc issuerdn = ca.getSubjectDN();
1254
1255
1256        try{
1257            CA cadata = ca.getCA();
1258
1259            // Revoke CA certificate
1260
getCertificateStoreSession().revokeCertificate(admin, cadata.getCACertificate(), cadata.getCRLPublishers(), reason);
1261             // Revoke all certificates generated by CA
1262
if(cadata.getStatus() != SecConst.CA_EXTERNAL){
1263              getCertificateStoreSession().revokeAllCertByCA(admin, issuerdn, RevokedCertInfo.REVOKATION_REASON_CACOMPROMISE);
1264              getCRLCreateSession().run(admin, issuerdn);
1265            }
1266            
1267            cadata.setRevokationReason(reason);
1268            cadata.setRevokationDate(new Date JavaDoc());
1269            if(cadata.getStatus() != SecConst.CA_EXTERNAL){
1270              ca.setStatus(SecConst.CA_REVOKED);
1271            }
1272            ca.setCA(cadata);
1273
1274        }catch(Exception JavaDoc e){
1275            String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorrevoke", ca.getName());
1276            getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAREVOKED,msg,e);
1277            throw new EJBException JavaDoc(e);
1278        }
1279
1280        String JavaDoc msg = intres.getLocalizedMessage("caadmin.revokedca", ca.getName(), new Integer JavaDoc(reason));
1281        getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_INFO_CAREVOKED,msg);
1282    } // revokeCA
1283

1284    /**
1285     * Method that should be used when upgrading from EJBCA 3.1 to EJBCA 3.2, changes class name of
1286     * nCipher HardToken HSMs after code re-structure.
1287     *
1288     * @param admin Administrator probably Admin.TYPE_CACOMMANDLINE_USER
1289     * @param caid id of CA to upgrade
1290     *
1291     * @ejb.interface-method
1292     */

1293    public void upgradeFromOldCAHSMKeyStore(Admin admin, int caid){
1294        try{
1295            // check authorization
1296
if(admin.getAdminType() != Admin.TYPE_CACOMMANDLINE_USER)
1297              getAuthorizationSession().isAuthorizedNoLog(admin,"/super_administrator");
1298
1299            CADataLocal cadata = cadatahome.findByPrimaryKey(new Integer JavaDoc(caid));
1300            CA ca = cadata.getCA();
1301            CAToken token = ca.getCAToken();
1302            CATokenInfo tokeninfo = token.getCATokenInfo();
1303            HardCATokenInfo htokeninfo = null;
1304            if (tokeninfo instanceof HardCATokenInfo) {
1305                error("(this is not an error) Found hard token for ca with id: "+caid);
1306                htokeninfo = (HardCATokenInfo)tokeninfo;
1307            } else {
1308                error("(this is not an error) No need to update soft token for ca with id: "+caid);
1309            }
1310            if (htokeninfo != null) {
1311                String JavaDoc oldtoken = htokeninfo.getClassPath();
1312                if (oldtoken.equals("se.anatom.ejbca.ca.caadmin.hardcatokens.NFastCAToken")
1313                        || oldtoken.equals("se.primeKey.caToken.nFast.NFastCAToken")) {
1314                    htokeninfo.setClassPath("org.ejbca.core.model.ca.catoken.NFastCAToken");
1315                    error("(this is not an error) Updated catoken classpath ("+oldtoken+") for ca with id: "+caid);
1316                    token.updateCATokenInfo(htokeninfo);
1317                    ca.setCAToken(token);
1318                    cadata.setCA(ca);
1319                } else {
1320                    error("(this is not an error) No need to update catoken classpath ("+oldtoken+") for ca with id: "+caid);
1321                }
1322            }
1323        }catch(Exception JavaDoc e){
1324            error("An error occured when trying to upgrade hard token classpath: ", e);
1325            getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CACREATED,"An error occured when trying to upgrade hard token classpath", e);
1326            throw new EJBException JavaDoc(e);
1327        }
1328
1329    } // upgradeFromOldCAHSMKeyStore
1330

1331    /**
1332     * Method that is used to create a new CA from an imported keystore from another type of CA, for example OpenSSL.
1333     *
1334     * @param admin Administrator
1335     * @param caname the CA-name (human readable) the newly created CA will get
1336     * @param p12file a byte array of old server p12 file.
1337     * @param keystorepass used to unlock the keystore.
1338     * @param privkeypass used to unlock the private key.
1339     * @param privateSignatureKeyAlias the alias for the private key in the keystore.
1340     * @param privateEncryptionKeyAlias the alias for the private encryption key in the keystore
1341     *
1342     * @ejb.interface-method
1343     */

1344    public void importCAFromKeyStore(Admin admin, String JavaDoc caname, byte[] p12file, char[] keystorepass,
1345                                         char[] privkeypass, String JavaDoc privateSignatureKeyAlias, String JavaDoc privateEncryptionKeyAlias) throws Exception JavaDoc {
1346        try{
1347            // check authorization
1348
if(admin.getAdminType() != Admin.TYPE_CACOMMANDLINE_USER) {
1349                getAuthorizationSession().isAuthorizedNoLog(admin, AvailableAccessRules.ROLE_SUPERADMINISTRATOR);
1350            }
1351            // load keystore
1352
java.security.KeyStore JavaDoc keystore=KeyStore.getInstance("PKCS12", "BC");
1353            keystore.load(new java.io.ByteArrayInputStream JavaDoc(p12file),keystorepass);
1354            // Extract signarture keys
1355
if ( privateSignatureKeyAlias == null || !keystore.isKeyEntry(privateSignatureKeyAlias) ) {
1356                throw new Exception JavaDoc("Alias \"" + privateSignatureKeyAlias + "\" not found.");
1357            }
1358            Certificate JavaDoc[] signatureCertChain = KeyTools.getCertChain(keystore, privateSignatureKeyAlias);
1359            if (signatureCertChain.length < 1) {
1360                String JavaDoc msg = "Cannot load certificate chain with alias " + privateSignatureKeyAlias;
1361                log.error(msg);
1362                throw new Exception JavaDoc(msg);
1363            }
1364            ArrayList JavaDoc certificatechain = new ArrayList JavaDoc();
1365            for(int i=0;i< signatureCertChain.length;i++){
1366                certificatechain.add(signatureCertChain[i]);
1367            }
1368            X509Certificate JavaDoc caSignatureCertificate = (X509Certificate JavaDoc) signatureCertChain[0];
1369            if ( caSignatureCertificate.getKeyUsage() != null ) {
1370                if (!caSignatureCertificate.getKeyUsage()[0] || !caSignatureCertificate.getKeyUsage()[5]) {
1371                    String JavaDoc msg = "Key assigned to alias \"" + privateSignatureKeyAlias + "\" cannot be used for signatures. Key usage vector is:";
1372                        for (int i=0; i<9; i++) {
1373                            msg += " " + caSignatureCertificate.getKeyUsage()[i];
1374                        }
1375                    log.error(msg);
1376                    throw new Exception JavaDoc(msg);
1377                }
1378            } else {
1379                log.warn("No key usage vector found for \"" + privateSignatureKeyAlias + "\". Assuming it is valid for signatures." );
1380            }
1381            PublicKey JavaDoc p12PublicSignatureKey = caSignatureCertificate.getPublicKey();
1382            PrivateKey JavaDoc p12PrivateSignatureKey = null;
1383            if ( p12PublicSignatureKey instanceof RSAPublicKey JavaDoc ) {
1384                p12PrivateSignatureKey = (PrivateKey JavaDoc) keystore.getKey( privateSignatureKeyAlias, privkeypass);
1385            } else {
1386                p12PrivateSignatureKey = (ECPrivateKey) keystore.getKey( privateSignatureKeyAlias, privkeypass);
1387                log.debug("ImportSignatureKeyAlgorithm (expecting ECDSA)="+((ECPrivateKey) keystore.getKey( privateSignatureKeyAlias, privkeypass)).getAlgorithm());
1388            }
1389            // Extract encryption keys
1390
PrivateKey JavaDoc p12PrivateEncryptionKey = null;
1391            PublicKey JavaDoc p12PublicEncryptionKey = null;
1392            X509Certificate JavaDoc caEncryptionCertificate = null;
1393            if (privateEncryptionKeyAlias != null) {
1394                if ( !keystore.isKeyEntry(privateEncryptionKeyAlias) ) {
1395                    throw new Exception JavaDoc("Alias \"" + privateEncryptionKeyAlias + "\" not found.");
1396                }
1397                Certificate JavaDoc[] encryptionCertChain = KeyTools.getCertChain(keystore, privateEncryptionKeyAlias);
1398                if (encryptionCertChain.length < 1) {
1399                    String JavaDoc msg = "Cannot load certificate chain with alias " + privateEncryptionKeyAlias;
1400                    log.error(msg);
1401                    throw new Exception JavaDoc(msg);
1402                }
1403                caEncryptionCertificate = (X509Certificate JavaDoc) encryptionCertChain[0];
1404                if ( caEncryptionCertificate.getKeyUsage() != null ) {
1405                    if ( !caEncryptionCertificate.getKeyUsage()[2] ) {
1406                        String JavaDoc msg = "Key asigned to alias \"" + privateEncryptionKeyAlias + "\" cannot be used for key encipherment. Key usage vector is:";
1407                        for (int i=0; i<caEncryptionCertificate.getKeyUsage().length; i++) {
1408                            msg += " " + caEncryptionCertificate.getKeyUsage()[i];
1409                        }
1410                        log.error(msg);
1411                        throw new Exception JavaDoc(msg);
1412                    }
1413                } else {
1414                    log.warn("No key usage vector found for \"" + privateEncryptionKeyAlias + "\". Assuming it is valid for signatures." );
1415                }
1416                p12PrivateEncryptionKey = (PrivateKey JavaDoc) keystore.getKey( privateEncryptionKeyAlias, privkeypass);
1417                p12PublicEncryptionKey = caEncryptionCertificate.getPublicKey();
1418            }
1419            // Transform into token
1420
CAToken catoken = new SoftCAToken();
1421            ((SoftCAToken) catoken).importKeysFromP12(p12PrivateSignatureKey, p12PublicSignatureKey, p12PrivateEncryptionKey,
1422                        p12PublicEncryptionKey, signatureCertChain);
1423            log.debug("CA-Info: "+catoken.getCATokenInfo().getSignatureAlgorithm() + " " + catoken.getCATokenInfo().getEncryptionAlgorithm());
1424            // Create a X509CA
1425
int signedby = CAInfo.SIGNEDBYEXTERNALCA;
1426            int certprof = SecConst.CERTPROFILE_FIXED_SUBCA;
1427            String JavaDoc description = "Imported external signed CA";
1428            if(signatureCertChain.length == 1) {
1429                if (verifyIssuer(caSignatureCertificate, caSignatureCertificate)) {
1430                    signedby = CAInfo.SELFSIGNED;
1431                    certprof = SecConst.CERTPROFILE_FIXED_ROOTCA;
1432                    description = "Imported root CA";
1433                } else {
1434                    // A less strict strategy can be to assume certificate signed
1435
// by an external CA. Useful if admin user forgot to create a full
1436
// certificate chain in PKCS#12 package.
1437
log.error("Cannot import CA " + caSignatureCertificate.getSubjectDN().getName()
1438                            + ": certificate " + caSignatureCertificate.getSerialNumber()
1439                            + " is not self-signed.");
1440                    throw new Exception JavaDoc("Cannot import CA "
1441                            + caSignatureCertificate.getSubjectDN().getName()
1442                            + ": certificate is not self-signed. Check "
1443                            + "certificate chain in PKCS#12");
1444                }
1445            } else if (signatureCertChain.length > 1){
1446                Collection JavaDoc cas = getAvailableCAs(admin);
1447                Iterator JavaDoc iter = cas.iterator();
1448                // Assuming certificate chain in forward direction (from target
1449
// to most-trusted CA). Multiple CA chains can contains the
1450
// issuer certificate; so only the chain where target certificate
1451
// is the issuer will be selected.
1452
while (iter.hasNext()) {
1453                    int caid = ((Integer JavaDoc)iter.next()).intValue();
1454                    CAInfo superCaInfo = getCAInfo(admin, caid);
1455                    Iterator JavaDoc i = superCaInfo.getCertificateChain().iterator();
1456                    if (i.hasNext()) {
1457                        X509Certificate JavaDoc superCaCert = (X509Certificate JavaDoc)i.next();
1458                        if (verifyIssuer(caSignatureCertificate, superCaCert)) {
1459                            signedby = caid;
1460                            description = "Imported sub CA";
1461                            break;
1462                        }
1463                    }
1464                }
1465            }
1466            // Create and active OSCP CA Service.
1467
String JavaDoc keyAlgorithm = CATokenConstants.KEYALGORITHM_RSA;
1468            String JavaDoc keySpecification = "2048";
1469            if (!(p12PublicSignatureKey instanceof RSAPublicKey JavaDoc)) {
1470                Enumeration JavaDoc en = ECNamedCurveTable.getNames();
1471                while ( en.hasMoreElements() ) {
1472                    String JavaDoc currentCurveName = (String JavaDoc) en.nextElement();
1473                    if ( (ECNamedCurveTable.getParameterSpec(currentCurveName)).getCurve().equals( ((ECPrivateKey) p12PrivateSignatureKey).getParameters().getCurve() ) ) {
1474                        keySpecification = currentCurveName;
1475                        keyAlgorithm = CATokenConstants.KEYALGORITHM_ECDSA;
1476                        break;
1477                    }
1478                }
1479            }
1480            ArrayList JavaDoc extendedcaservices = new ArrayList JavaDoc();
1481            extendedcaservices.add(
1482                    new OCSPCAServiceInfo(ExtendedCAServiceInfo.STATUS_ACTIVE,
1483                                    "CN=OCSPSignerCertificate, " + caSignatureCertificate.getSubjectDN().toString(),
1484                                    "",
1485                                    keySpecification,
1486                                    keyAlgorithm));
1487            // Create and active XKMS CA Service.
1488
extendedcaservices.add(
1489                    new XKMSCAServiceInfo(ExtendedCAServiceInfo.STATUS_INACTIVE,
1490                                          "CN=XKMSCertificate, " + caSignatureCertificate.getSubjectDN().toString(),
1491                                          "",
1492                                          keySpecification,
1493                                          keyAlgorithm));
1494            // Create and active CMS CA Service.
1495
extendedcaservices.add(
1496                    new CmsCAServiceInfo(ExtendedCAServiceInfo.STATUS_INACTIVE,
1497                                          "CN=CMSCertificate, " + caSignatureCertificate.getSubjectDN().toString(),
1498                                          "",
1499                                          keySpecification,
1500                                          keyAlgorithm));
1501            int validity = (int)((caSignatureCertificate.getNotAfter().getTime() - caSignatureCertificate.getNotBefore().getTime()) / (24*3600*1000));
1502            X509CAInfo cainfo = new X509CAInfo(caSignatureCertificate.getSubjectDN().toString(),
1503                                               caname, SecConst.CA_ACTIVE, new Date JavaDoc(),
1504                                               "", certprof,
1505                                               validity,
1506                                               caSignatureCertificate.getNotAfter(), // Expiretime
1507
CAInfo.CATYPE_X509,
1508                                               signedby,
1509                                               certificatechain,
1510                                               catoken.getCATokenInfo(),
1511                                               description,
1512                                               -1, null, // revokationreason, revokationdate
1513
"", // PolicyId
1514
24, // CRLPeriod
1515
0, // CRLIssuePeriod
1516
10, // CRLOverlapTime
1517
new ArrayList JavaDoc(),
1518                                               true, // Authority Key Identifier
1519
false, // Authority Key Identifier Critical
1520
true, // CRL Number
1521
false, // CRL Number Critical
1522
"", // Default CRL Dist Point
1523
"", // Default CRL Issuer
1524
"", // Default OCSP Service Locator
1525
true, // Finish User
1526
extendedcaservices,
1527                                               false, // use default utf8 settings
1528
new ArrayList JavaDoc(), // Approvals Settings
1529
1, // Number of Req approvals
1530
false); // Use UTF8 subject DN by default
1531
X509CA ca = new X509CA(cainfo);
1532            ca.setCAToken(catoken);
1533            ca.setCertificateChain(certificatechain);
1534            log.debug("CA-Info: "+catoken.getCATokenInfo().getSignatureAlgorithm() + " " + ca.getCAToken().getCATokenInfo().getEncryptionAlgorithm());
1535            // Publish CA certificates.
1536
getSignSession().publishCACertificate(admin, ca.getCertificateChain(), ca.getCRLPublishers());
1537            // activate External CA Services
1538
Iterator JavaDoc iter = cainfo.getExtendedCAServiceInfos().iterator();
1539            while(iter.hasNext()){
1540                ExtendedCAServiceInfo info = (ExtendedCAServiceInfo) iter.next();
1541                if(info instanceof OCSPCAServiceInfo){
1542                    try{
1543                        ca.initExternalService(ExtendedCAServiceInfo.TYPE_OCSPEXTENDEDSERVICE, ca);
1544                        ArrayList JavaDoc ocspcertificate = new ArrayList JavaDoc();
1545                        ocspcertificate.add(((OCSPCAServiceInfo) ca.getExtendedCAServiceInfo(ExtendedCAServiceInfo.TYPE_OCSPEXTENDEDSERVICE)).getOCSPSignerCertificatePath().get(0));
1546                        getSignSession().publishCACertificate(admin, ocspcertificate, ca.getCRLPublishers());
1547                    }catch(Exception JavaDoc fe){
1548                        getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CACREATED,"Couldn't Create ExternalCAService.",fe);
1549                        throw new EJBException JavaDoc(fe);
1550                    }
1551                }
1552                if(info instanceof XKMSCAServiceInfo){
1553                    try{
1554                        ca.initExternalService(ExtendedCAServiceInfo.TYPE_XKMSEXTENDEDSERVICE, ca);
1555                        ArrayList JavaDoc xkmscertificate = new ArrayList JavaDoc();
1556                        xkmscertificate.add(((XKMSCAServiceInfo) ca.getExtendedCAServiceInfo(ExtendedCAServiceInfo.TYPE_XKMSEXTENDEDSERVICE)).getXKMSSignerCertificatePath().get(0));
1557                        getSignSession().publishCACertificate(admin, xkmscertificate, ca.getCRLPublishers());
1558                    }catch(Exception JavaDoc fe){
1559                        getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CACREATED,"Couldn't Create ExternalCAService.",fe);
1560                        throw new EJBException JavaDoc(fe);
1561                    }
1562                }
1563                if(info instanceof CmsCAServiceInfo){
1564                    try{
1565                        ca.initExternalService(ExtendedCAServiceInfo.TYPE_CMSEXTENDEDSERVICE, ca);
1566                        ArrayList JavaDoc cmscertificate = new ArrayList JavaDoc();
1567                        cmscertificate.add(((CmsCAServiceInfo) ca.getExtendedCAServiceInfo(ExtendedCAServiceInfo.TYPE_CMSEXTENDEDSERVICE)).getCertificatePath().get(0));
1568                        getSignSession().publishCACertificate(admin, cmscertificate, ca.getCRLPublishers());
1569                    }catch(Exception JavaDoc fe){
1570                        getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CACREATED,"Couldn't Create ExternalCAService.",fe);
1571                        throw new EJBException JavaDoc(fe);
1572                    }
1573                }
1574            }
1575            // Store CA in database.
1576
cadatahome.create(cainfo.getSubjectDN(), cainfo.getName(), SecConst.CA_ACTIVE, ca);
1577            this.getCRLCreateSession().run(admin,cainfo.getSubjectDN());
1578            getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_INFO_CACREATED,"CA imported successfully from old P12 file, status: " + ca.getStatus());
1579        } catch(Exception JavaDoc e) {
1580            getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CACREATED,"An error occured when trying to import CA from old P12 file", e);
1581            throw new EJBException JavaDoc(e);
1582        }
1583    } // importCAFromKeyStore
1584

1585    /**
1586     * Exports a CA to file. The method only works for soft tokens.
1587     *
1588     * @param admin Administrator
1589     * @param caname the CA-name (human readable) the CA
1590     * @param keystorepass used to lock the keystore.
1591     * @param privkeypass used to lock the private key.
1592     * @param privateSignatureKeyAlias the alias for the private signature key in the keystore.
1593     * @param privateEncryptionKeyAlias the alias for the private encryption key in teh keystore
1594     *
1595     * @return A byte array of the CAs p12.
1596     *
1597     * @ejb.interface-method
1598     */

1599    public byte[] exportCAKeyStore(Admin admin, String JavaDoc caname, char[] keystorepass, char[] privkeypass, String JavaDoc privateSignatureKeyAlias,
1600            String JavaDoc privateEncryptionKeyAlias) throws Exception JavaDoc {
1601        log.debug(">exportCAKeyStore");
1602        try {
1603            CA thisCa = cadatahome.findByName(caname).getCA();
1604            // Make sure we are not trying to export a hard or invalid token
1605
if ( thisCa.getCAType() != CATokenInfo.CATOKENTYPE_P12 ) {
1606                throw new Exception JavaDoc("Cannot export anything but a soft token.");
1607            }
1608            // Check authorization
1609
if(admin.getAdminType() != Admin.TYPE_CACOMMANDLINE_USER) {
1610                getAuthorizationSession().isAuthorizedNoLog(admin, AvailableAccessRules.ROLE_SUPERADMINISTRATOR);
1611            }
1612            // Fetch keys
1613
CAToken thisCAToken = thisCa.getCAToken();
1614            KeyStore JavaDoc keystore = KeyStore.getInstance("PKCS12", "BC");
1615            keystore.load(null, keystorepass);
1616            
1617            PrivateKey JavaDoc p12PrivateEncryptionKey = ((SoftCAToken) thisCAToken).getPrivateKey(SecConst.CAKEYPURPOSE_KEYENCRYPT);
1618            PublicKey JavaDoc p12PublicEncryptionKey = ((SoftCAToken) thisCAToken).getPublicKey(SecConst.CAKEYPURPOSE_KEYENCRYPT);
1619            PrivateKey JavaDoc p12PrivateCertSignKey = ((SoftCAToken) thisCAToken).getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN);
1620            PrivateKey JavaDoc p12PrivateCRLSignKey = ((SoftCAToken) thisCAToken).getPrivateKey(SecConst.CAKEYPURPOSE_CRLSIGN);
1621            if ( !p12PrivateCertSignKey.equals(p12PrivateCRLSignKey) ) {
1622                throw new Exception JavaDoc("Assertion of equal signature keys failed.");
1623            }
1624            // Load keys into keystore
1625
X509Certificate JavaDoc[] certificateChainSignature = (X509Certificate JavaDoc[]) thisCa.getCertificateChain().toArray(new X509Certificate JavaDoc[0]);
1626            X509Certificate JavaDoc[] certificateChainEncryption = new X509Certificate JavaDoc[1];
1627            //certificateChainSignature[0].getSigAlgName(),
1628
// generate dummy certificate for encryption key.
1629
certificateChainEncryption[0] = CertTools.genSelfCertForPurpose("CN=dummy2", 36500, null, p12PrivateEncryptionKey, p12PublicEncryptionKey,
1630                    thisCAToken.getCATokenInfo().getEncryptionAlgorithm(), true, X509KeyUsage.keyEncipherment);
1631            log.debug("Exporting with sigAlgorithm "+certificateChainSignature[0].getSigAlgName()+"encAlgorithm="+thisCAToken.getCATokenInfo().getEncryptionAlgorithm());
1632            if ( keystore.isKeyEntry(privateSignatureKeyAlias) ) {
1633                throw new Exception JavaDoc("Key \"" + privateSignatureKeyAlias + "\"already exists in keystore.");
1634            }
1635            if ( keystore.isKeyEntry(privateEncryptionKeyAlias) ) {
1636                throw new Exception JavaDoc("Key \"" + privateEncryptionKeyAlias + "\"already exists in keystore.");
1637            }
1638
1639            keystore.setKeyEntry(privateSignatureKeyAlias, p12PrivateCertSignKey, privkeypass, certificateChainSignature);
1640            keystore.setKeyEntry(privateEncryptionKeyAlias, p12PrivateEncryptionKey, privkeypass, certificateChainEncryption);
1641            // Return keystore as byte array and clean up
1642
ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
1643            keystore.store(baos, keystorepass);
1644            if ( keystore.isKeyEntry(privateSignatureKeyAlias) ) {
1645                keystore.deleteEntry(privateSignatureKeyAlias);
1646            }
1647            if ( keystore.isKeyEntry(privateEncryptionKeyAlias) ) {
1648                keystore.deleteEntry(privateEncryptionKeyAlias);
1649            }
1650            getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_INFO_CAEXPORTED,"CA exported successfully from to P12 file.");
1651            return baos.toByteArray();
1652        } catch(Exception JavaDoc e){
1653            getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEXPORTED,"An error occured when trying to export CA to P12 file", e);
1654            throw new EJBException JavaDoc(e);
1655        }
1656    } // exportCAKeyStore
1657

1658
1659    /**
1660     * Method returning a Collection of Certificate of all CA certificates known to the system.
1661     * Certificates for External CAs or CAs that are awaiting certificate response are not returned, because we don't have certificates for them.
1662     * Uses getAvailableCAs to list CAs.
1663     *
1664     * @ejb.transaction type="Supports"
1665     * @ejb.interface-method
1666     */

1667    public Collection JavaDoc getAllCACertificates(Admin admin){
1668      ArrayList JavaDoc returnval = new ArrayList JavaDoc();
1669
1670      try{
1671          Collection JavaDoc caids = getAvailableCAs(admin);
1672          Iterator JavaDoc iter = caids.iterator();
1673          while(iter.hasNext()){
1674              Integer JavaDoc caid = (Integer JavaDoc)iter.next();
1675              CADataLocal cadata = cadatahome.findByPrimaryKey(caid);
1676              CA ca = cadata.getCA();
1677              if (log.isDebugEnabled()) {
1678                  debug("Getting certificate chain for CA: "+ca.getName()+", "+ca.getCAId());
1679              }
1680              returnval.add(ca.getCACertificate());
1681          }
1682      }catch(javax.ejb.FinderException JavaDoc fe) {
1683          error("Can't find CA: ", fe);
1684      } catch(UnsupportedEncodingException JavaDoc uee){
1685          throw new EJBException JavaDoc(uee);
1686      } catch(IllegalKeyStoreException e){
1687          throw new EJBException JavaDoc(e);
1688      }
1689      return returnval;
1690    } // getAllCACertificates
1691

1692    /**
1693     * Check if password is a the rigth keystore password
1694     *
1695     * @param admin Administrator
1696     * @param capassword used to unlock the keystore.
1697     *
1698     * @ejb.interface-method
1699     */

1700    public boolean isKeyStorePassword(Admin admin, String JavaDoc capassword) {
1701        try {
1702            if(admin.getAdminType() != Admin.TYPE_CACOMMANDLINE_USER) {
1703                getAuthorizationSession().isAuthorizedNoLog(admin,AvailableAccessRules.ROLE_SUPERADMINISTRATOR);
1704            }
1705        } catch (AuthorizationDeniedException e) {
1706            return false;
1707        }
1708        String JavaDoc keyStorePass = ServiceLocator.getInstance().getString("java:comp/env/keyStorePass");
1709        return ( keyStorePass.equals(capassword) );
1710    } // isKeyStorePassword
1711

1712    /**
1713     * Retrieve fingerprint for all keys as a String. Used for testing.
1714     *
1715     * @param admin Administrator
1716     * @param capassword used to unlock the keystore.
1717     * @throws Exception
1718     * @ejb.interface-method
1719     */

1720    public String JavaDoc getKeyFingerPrint(Admin admin, String JavaDoc caname) throws Exception JavaDoc {
1721        try {
1722            if(admin.getAdminType() != Admin.TYPE_CACOMMANDLINE_USER) {
1723                getAuthorizationSession().isAuthorizedNoLog(admin, AvailableAccessRules.ROLE_SUPERADMINISTRATOR);
1724            }
1725            CA thisCa;
1726            thisCa = cadatahome.findByName(caname).getCA();
1727
1728            // Make sure we are not trying to export a hard or invalid token
1729
if ( thisCa.getCAType() != CATokenInfo.CATOKENTYPE_P12 ) {
1730                throw new Exception JavaDoc("Cannot extract fingerprint from a non-soft token.");
1731            }
1732            // Fetch keys
1733
CAToken thisCAToken = thisCa.getCAToken();
1734            PrivateKey JavaDoc p12PrivateEncryptionKey = ((SoftCAToken) thisCAToken).getPrivateKey(SecConst.CAKEYPURPOSE_KEYENCRYPT);
1735            PrivateKey JavaDoc p12PrivateCertSignKey = ((SoftCAToken) thisCAToken).getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN);
1736            PrivateKey JavaDoc p12PrivateCRLSignKey = ((SoftCAToken) thisCAToken).getPrivateKey(SecConst.CAKEYPURPOSE_CRLSIGN);
1737            MessageDigest JavaDoc md = MessageDigest.getInstance("SHA1");
1738            md.update(p12PrivateEncryptionKey.getEncoded());
1739            md.update(p12PrivateCertSignKey.getEncoded());
1740            md.update(p12PrivateCRLSignKey.getEncoded());
1741            return new String JavaDoc(Hex.encode(md.digest()));
1742        } catch (Exception JavaDoc e) {
1743            throw new Exception JavaDoc(e);
1744        }
1745    } // getKeyFingerPrint
1746

1747    
1748    /**
1749     * Activates an 'Offline' CA Token and sets the CA status to acitve and ready for use again.
1750     * The admin must be authorized to "/ca_functionality/basic_functions/activate_ca" inorder to activate/deactivate.
1751     *
1752     * @param admin the adomistrator calling the method
1753     * @param caid the is of the ca to activate
1754     * @param the authorizationcode used to unlock the CA tokens private keys.
1755     *
1756     * @throws AuthorizationDeniedException it the administrator isn't authorized to activate the CA.
1757     * @throws CATokenAuthenticationFailedException if the current status of the ca or authenticationcode is wrong.
1758     * @throws CATokenOfflineException if the CA token is still offline when calling the method.
1759     *
1760     * @ejb.interface-method
1761     */

1762    public void activateCAToken(Admin admin, int caid, String JavaDoc authorizationcode) throws AuthorizationDeniedException, CATokenAuthenticationFailedException, CATokenOfflineException{
1763       // Authorize
1764
try{
1765            getAuthorizationSession().isAuthorizedNoLog(admin,AvailableAccessRules.REGULAR_ACTIVATECA);
1766        }catch(AuthorizationDeniedException ade){
1767            String JavaDoc msg = intres.getLocalizedMessage("caadmin.notauthorizedtoactivatetoken", new Integer JavaDoc(caid));
1768            getLogSession().log (admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_NOTAUTHORIZEDTORESOURCE,msg,ade);
1769            throw new AuthorizationDeniedException(msg);
1770        }
1771
1772        try{
1773            if(caid >=0 && caid <= CAInfo.SPECIALCAIDBORDER){
1774                String JavaDoc msg = intres.getLocalizedMessage("caadmin.erroractivatetoken", new Integer JavaDoc(caid));
1775                getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg);
1776                throw new CATokenAuthenticationFailedException(msg);
1777            }
1778            CADataLocal cadata = cadatahome.findByPrimaryKey(new Integer JavaDoc(caid));
1779            boolean cATokenDisconnected = false;
1780            try{
1781              if(cadata.getCA().getCAToken().getCATokenInfo() instanceof HardCATokenInfo){
1782                if(((HardCATokenInfo) cadata.getCA().getCAToken().getCATokenInfo()).getCATokenStatus() == IHardCAToken.STATUS_OFFLINE){
1783                    cATokenDisconnected = true;
1784                }
1785              }
1786            }catch (IllegalKeyStoreException e) {
1787                String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorreadingtoken", new Integer JavaDoc(caid));
1788                log.error(msg,e);
1789            } catch (UnsupportedEncodingException JavaDoc e) {
1790                String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorreadingtoken", new Integer JavaDoc(caid));
1791                log.error(msg,e);
1792            }
1793            if(cadata.getStatus() == SecConst.CA_OFFLINE || cATokenDisconnected){
1794                try {
1795                    cadata.getCA().getCAToken().activate(authorizationcode);
1796                    cadata.setStatus(SecConst.CA_ACTIVE);
1797                    // Invalidate CA cache to refresh information
1798
CACacheManager.instance().removeCA(cadata.getCaId().intValue());
1799                    String JavaDoc msg = intres.getLocalizedMessage("caadmin.catokenactivated", cadata.getName());
1800                    getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_INFO_CAEDITED,msg);
1801                } catch (IllegalKeyStoreException e) {
1802                    throw new EJBException JavaDoc(e);
1803                } catch (UnsupportedEncodingException JavaDoc e) {
1804                    throw new EJBException JavaDoc(e);
1805                }
1806            }else{
1807                String JavaDoc msg = intres.getLocalizedMessage("caadmin.errornotoffline", cadata.getName());
1808                getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg);
1809                throw new CATokenAuthenticationFailedException(msg);
1810            }
1811        }catch(javax.ejb.FinderException JavaDoc fe) {
1812            String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorcanotfound", new Integer JavaDoc(caid));
1813            getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg);
1814            throw new EJBException JavaDoc(fe);
1815        }
1816    }
1817
1818    /**
1819     * Deactivates an 'active' CA token and sets the CA status to offline.
1820     * The admin must be authorized to "/ca_functionality/basic_functions/activate_ca" inorder to activate/deactivate.
1821     *
1822     * @param admin the adomistrator calling the method
1823     * @param caid the is of the ca to activate.
1824     *
1825     * @throws AuthorizationDeniedException it the administrator isn't authorized to activate the CA.
1826     * @throws EjbcaException if the given caid couldn't be found or its status is wrong.
1827     *
1828     * @ejb.interface-method
1829     */

1830    public void deactivateCAToken(Admin admin, int caid) throws AuthorizationDeniedException, EjbcaException{
1831       // Authorize
1832
try{
1833            getAuthorizationSession().isAuthorizedNoLog(admin,AvailableAccessRules.REGULAR_ACTIVATECA);
1834        }catch(AuthorizationDeniedException ade){
1835            String JavaDoc msg = intres.getLocalizedMessage("caadmin.notauthorizedtodeactivatetoken", new Integer JavaDoc(caid));
1836            getLogSession().log (admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_NOTAUTHORIZEDTORESOURCE,msg,ade);
1837            throw new AuthorizationDeniedException(msg);
1838        }
1839
1840        try{
1841            if(caid >=0 && caid <= CAInfo.SPECIALCAIDBORDER){
1842                // This should never happen.
1843
String JavaDoc msg = intres.getLocalizedMessage("caadmin.errordeactivatetoken", new Integer JavaDoc(caid));
1844                getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg);
1845                throw new EjbcaException(msg);
1846            }
1847            CADataLocal cadata = cadatahome.findByPrimaryKey(new Integer JavaDoc(caid));
1848            if(cadata.getStatus() == SecConst.CA_ACTIVE){
1849                try {
1850                    cadata.getCA().getCAToken().deactivate();
1851                    cadata.setStatus(SecConst.CA_OFFLINE);
1852                    // Invalidate CA cache to refresh information
1853
CACacheManager.instance().removeCA(cadata.getCaId().intValue());
1854                    String JavaDoc msg = intres.getLocalizedMessage("caadmin.catokendeactivated", cadata.getName());
1855                    getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_INFO_CAEDITED,msg);
1856                } catch (IllegalKeyStoreException e) {
1857                    throw new EJBException JavaDoc(e);
1858                } catch (UnsupportedEncodingException JavaDoc e) {
1859                    throw new EJBException JavaDoc(e);
1860                }
1861            }else{
1862                String JavaDoc msg = intres.getLocalizedMessage("caadmin.errornotonline", cadata.getName());
1863                getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg);
1864                throw new EjbcaException(msg);
1865            }
1866        }catch(javax.ejb.FinderException JavaDoc fe) {
1867            String JavaDoc msg = intres.getLocalizedMessage("caadmin.errorcanotfound", new Integer JavaDoc(caid));
1868            getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg);
1869            throw new EJBException JavaDoc(fe);
1870        }
1871    }
1872
1873    /**
1874     * Method used to check if certificate profile id exists in any CA.
1875     *
1876     * @ejb.interface-method
1877     */

1878    public boolean exitsCertificateProfileInCAs(Admin admin, int certificateprofileid){
1879      boolean returnval = false;
1880      try{
1881        Collection JavaDoc result = cadatahome.findAll();
1882        Iterator JavaDoc iter = result.iterator();
1883        while(iter.hasNext()){
1884          CADataLocal cadata = (CADataLocal) iter.next();
1885          returnval = returnval || (cadata.getCA().getCertificateProfileId() == certificateprofileid);
1886        }
1887      }catch(javax.ejb.FinderException JavaDoc fe){}
1888       catch(java.io.UnsupportedEncodingException JavaDoc e){}
1889       catch(IllegalKeyStoreException e){}
1890
1891      return returnval;
1892    } // exitsCertificateProfileInCAs
1893

1894
1895    /**
1896     * Method used to check if publishers id exists in any CAs CRLPublishers Collection.
1897     *
1898     * @ejb.interface-method
1899     */

1900    public boolean exitsPublisherInCAs(Admin admin, int publisherid){
1901      boolean returnval = false;
1902      try{
1903        Collection JavaDoc result = cadatahome.findAll();
1904        Iterator JavaDoc iter = result.iterator();
1905        while(iter.hasNext()){
1906          CADataLocal cadata = (CADataLocal) iter.next();
1907          Iterator JavaDoc pubiter = cadata.getCA().getCRLPublishers().iterator();
1908          while(pubiter.hasNext()){
1909              Integer JavaDoc pubInt = (Integer JavaDoc)pubiter.next();
1910              returnval = returnval || (pubInt.intValue() == publisherid);
1911          }
1912        }
1913      }catch(javax.ejb.FinderException JavaDoc fe){}
1914       catch(java.io.UnsupportedEncodingException JavaDoc e){}
1915       catch(IllegalKeyStoreException e){}
1916        
1917      return returnval;
1918    } // exitsPublisherInCAs
1919

1920    private boolean authorizedToCA(Admin admin, int caid){
1921      boolean returnval = false;
1922      try{
1923        returnval = getAuthorizationSession().isAuthorizedNoLog(admin, AvailableAccessRules.CAPREFIX + caid);
1924      }catch(AuthorizationDeniedException e){}
1925      return returnval;
1926    }
1927
1928    //
1929
// Private methods
1930
//
1931

1932    /** Gets connection to log session bean
1933     */

1934    private ILogSessionLocal getLogSession() {
1935        if(logsession == null){
1936            try{
1937                ILogSessionLocalHome home = (ILogSessionLocalHome) getLocator().getLocalHome(ILogSessionLocalHome.COMP_NAME);
1938                logsession = home.create();
1939            }catch(Exception JavaDoc e){
1940                throw new EJBException JavaDoc(e);
1941            }
1942        }
1943        return logsession;
1944    } //getLogSession
1945

1946
1947    /** Gets connection to authorization session bean
1948     * @return Connection
1949     */

1950    private IAuthorizationSessionLocal getAuthorizationSession() {
1951        if(authorizationsession == null){
1952            try{
1953                IAuthorizationSessionLocalHome home = (IAuthorizationSessionLocalHome) getLocator().getLocalHome(IAuthorizationSessionLocalHome.COMP_NAME);
1954                authorizationsession = home.create();
1955            }catch(Exception JavaDoc e){
1956                throw new EJBException JavaDoc(e);
1957            }
1958        }
1959        return authorizationsession;
1960    } //getAuthorizationSession
1961

1962    /** Gets connection to crl create session bean
1963     * @return Connection
1964     */

1965    private ICreateCRLSessionLocal getCRLCreateSession() {
1966      if(jobrunner == null){
1967         try{
1968            ICreateCRLSessionLocalHome home = (ICreateCRLSessionLocalHome) getLocator().getLocalHome(ICreateCRLSessionLocalHome.COMP_NAME);
1969            jobrunner = home.create();
1970         }catch(Exception JavaDoc e){
1971            throw new EJBException JavaDoc(e);
1972         }
1973      }
1974      return jobrunner;
1975    }
1976
1977    /** Gets connection to certificate store session bean
1978     * @return Connection
1979     */

1980    private ICertificateStoreSessionLocal getCertificateStoreSession() {
1981        if(certificatestoresession == null){
1982            try{
1983                ICertificateStoreSessionLocalHome home = (ICertificateStoreSessionLocalHome) getLocator().getLocalHome(ICertificateStoreSessionLocalHome.COMP_NAME);
1984                certificatestoresession = home.create();
1985            }catch(Exception JavaDoc e){
1986                throw new EJBException JavaDoc(e);
1987            }
1988        }
1989        return certificatestoresession;
1990    } //getCertificateStoreSession
1991

1992    /** Gets connection to sign session bean
1993     * @return Connection
1994     */

1995    private ISignSessionLocal getSignSession() {
1996        if(signsession == null){
1997            try{
1998                ISignSessionLocalHome signsessionhome = (ISignSessionLocalHome) getLocator().getLocalHome(ISignSessionLocalHome.COMP_NAME);
1999                signsession = signsessionhome.create();
2000            }catch(Exception JavaDoc e){
2001                throw new EJBException JavaDoc(e);
2002            }
2003        }
2004        return signsession;
2005    } //getSignSession
2006

2007    /** Check if subject certificate is signed by issuer certificate. Used in
2008     * @see #upgradeFromOldCAKeyStore(Admin, String, byte[], char[], char[], String).
2009     * This method does a lazy check: if signature verification failed for
2010     * any reason that prevent verification, e.g. signature algorithm not
2011     * supported, method returns false.
2012     * Author: Marco Ferrante
2013     *
2014     * @param subject Subject certificate
2015     * @param issuer Issuer certificate
2016     * @return true if subject certificate is signed by issuer certificate
2017     * @throws java.lang.Exception
2018     */

2019    private boolean verifyIssuer(X509Certificate JavaDoc subject, X509Certificate JavaDoc issuer) throws Exception JavaDoc {
2020        try {
2021            PublicKey JavaDoc issuerKey = issuer.getPublicKey();
2022            subject.verify(issuerKey);
2023            return true;
2024        } catch (java.security.GeneralSecurityException JavaDoc e) {
2025            return false;
2026        }
2027    }
2028    
2029    /** Checks the signer validity given a CADataLocal object, as a side-effect marks the signer as expired if it is expired,
2030     * and throws an EJBException to the caller.
2031     *
2032     * @param admin administrator calling the method
2033     * @param signcadata a CADataLocal entity object of the signer to be checked
2034     * @throws UnsupportedEncodingException if there is an error getting the CA from the CADataLoca
2035     * @throws IllegalKeyStoreException l
2036     * @throws EJBException embedding a CertificateExpiredException or a CertificateNotYetValidException if the certificate has expired or is not yet valid
2037     */

2038    private void checkSignerValidity(Admin admin, CADataLocal signcadata) throws UnsupportedEncodingException JavaDoc, IllegalKeyStoreException {
2039        // Check validity of signers certificate
2040
X509Certificate JavaDoc signcert = (X509Certificate JavaDoc) signcadata.getCA().getCACertificate();
2041        try{
2042            signcert.checkValidity();
2043        }catch(CertificateExpiredException JavaDoc ce){
2044            // Signers Certificate has expired.
2045
signcadata.setStatus(SecConst.CA_EXPIRED);
2046            String JavaDoc msg = intres.getLocalizedMessage("signsession.caexpired", signcadata.getSubjectDN());
2047            getLogSession().log(admin, signcadata.getCaId().intValue(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg,ce);
2048            throw new EJBException JavaDoc(ce);
2049        }catch(CertificateNotYetValidException JavaDoc cve){
2050            String JavaDoc msg = intres.getLocalizedMessage("signsession.canotyetvalid", signcadata.getSubjectDN());
2051            getLogSession().log(admin, signcadata.getCaId().intValue(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CAEDITED,msg,cve);
2052            throw new EJBException JavaDoc(cve);
2053        }
2054    }
2055
2056    /**
2057     * Method to create certificate path and to check it's validity from a list of certificates.
2058     * The list of certificates should only contain one root certificate.
2059     *
2060     * @param certlist
2061     * @return the certificatepath
2062     */

2063    private Collection JavaDoc createCertChain(Collection JavaDoc certlist) throws CertPathValidatorException JavaDoc{
2064       ArrayList JavaDoc returnval = new ArrayList JavaDoc();
2065
2066       certlist = orderCertificateChain(certlist);
2067
2068        // set certificate chain
2069
TrustAnchor JavaDoc trustanchor = null;
2070       ArrayList JavaDoc calist = new ArrayList JavaDoc();
2071       Iterator JavaDoc iter = certlist.iterator();
2072       while(iter.hasNext()){
2073          Certificate JavaDoc next = (Certificate JavaDoc) iter.next();
2074          if(next instanceof X509Certificate JavaDoc && CertTools.isSelfSigned(((X509Certificate JavaDoc) next))){
2075              trustanchor = new TrustAnchor JavaDoc((X509Certificate JavaDoc) next, null);
2076          }
2077          else{
2078            calist.add(next);
2079          }
2080     }
2081
2082     if(calist.size() == 0){
2083        // only one root cert, no certchain
2084
returnval.add(trustanchor.getTrustedCert());
2085     }else{
2086      try {
2087        HashSet JavaDoc trustancors = new HashSet JavaDoc();
2088        trustancors.add(trustanchor);
2089
2090        //CollectionCertStoreParameters ccsp = new CollectionCertStoreParameters( certlist );
2091
//CertStore store = CertStore.getInstance("Collection", ccsp );
2092

2093
2094        // Create the parameters for the validator
2095
PKIXParameters JavaDoc params = new PKIXParameters JavaDoc(trustancors);
2096
2097        // Disable CRL checking since we are not supplying any CRLs
2098
params.setRevocationEnabled(false);
2099        //params.addCertStore(store);
2100
params.setDate( new Date JavaDoc() );
2101        // Create the validator and validate the path
2102

2103        CertPathValidator JavaDoc certPathValidator
2104            = CertPathValidator.getInstance(CertPathValidator.getDefaultType(), "BC");
2105        CertificateFactory JavaDoc fact = CertTools.getCertificateFactory();
2106        CertPath JavaDoc certpath = fact.generateCertPath(calist);
2107
2108        iter = certpath.getCertificates().iterator();
2109
2110
2111        CertPathValidatorResult JavaDoc result = certPathValidator.validate(certpath, params);
2112
2113        // Get the CA used to validate this path
2114
PKIXCertPathValidatorResult JavaDoc pkixResult = (PKIXCertPathValidatorResult JavaDoc)result;
2115        returnval.addAll(certpath.getCertificates());
2116
2117        //c a.setRequestCertificateChain(certpath.getCertificates());
2118
TrustAnchor JavaDoc ta = pkixResult.getTrustAnchor();
2119        X509Certificate JavaDoc cert = ta.getTrustedCert();
2120        returnval.add(cert);
2121      } catch (CertPathValidatorException JavaDoc e) {
2122        throw e;
2123      } catch(Exception JavaDoc e){
2124        throw new EJBException JavaDoc(e);
2125      }
2126     }
2127
2128
2129     return returnval;
2130  }
2131
2132  /**
2133   * Method ordering a list of x509certificate into a certificate path with to ca at the end.
2134   * Does not check validity or verification of any kind, just ordering by issuerdn.
2135   * @param certlist list of certificates to order.
2136   * @return Collection with certificatechain.
2137   */

2138  private Collection JavaDoc orderCertificateChain(Collection JavaDoc certlist) throws CertPathValidatorException JavaDoc{
2139     ArrayList JavaDoc returnval = new ArrayList JavaDoc();
2140     X509Certificate JavaDoc rootca = null;
2141     HashMap JavaDoc cacertmap = new HashMap JavaDoc();
2142     Iterator JavaDoc iter = certlist.iterator();
2143     while(iter.hasNext()){
2144        X509Certificate JavaDoc cert = (X509Certificate JavaDoc) iter.next();
2145        if(CertTools.isSelfSigned(cert))
2146          rootca = cert;
2147        else
2148          cacertmap.put(cert.getIssuerDN().toString(),cert);
2149     }
2150
2151     if(rootca == null)
2152       throw new CertPathValidatorException JavaDoc("No root CA certificate found in certificatelist");
2153
2154     returnval.add(0,rootca);
2155     X509Certificate JavaDoc currentcert = rootca;
2156     int i =0;
2157     while(certlist.size() != returnval.size() && i <= certlist.size()){
2158        X509Certificate JavaDoc nextcert = (X509Certificate JavaDoc) cacertmap.get(currentcert.getSubjectDN().toString());
2159        if(nextcert == null)
2160          throw new CertPathValidatorException JavaDoc("Error building certificate path");
2161
2162        returnval.add(0,nextcert);
2163        currentcert = nextcert;
2164        i++;
2165     }
2166
2167     if(i > certlist.size())
2168      throw new CertPathValidatorException JavaDoc("Error building certificate path");
2169
2170
2171     return returnval;
2172  }
2173
2174
2175} //CAAdminSessionBean
2176
Popular Tags