KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ejbca > core > ejb > ca > store > CertificateDataUtil


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.store;
15
16 import java.math.BigInteger JavaDoc;
17 import java.security.cert.Certificate JavaDoc;
18 import java.security.cert.X509Certificate JavaDoc;
19 import java.sql.Connection JavaDoc;
20 import java.sql.PreparedStatement JavaDoc;
21 import java.sql.ResultSet JavaDoc;
22 import java.util.ArrayList JavaDoc;
23 import java.util.Collection JavaDoc;
24 import java.util.Date JavaDoc;
25 import java.util.Iterator JavaDoc;
26
27 import javax.ejb.CreateException JavaDoc;
28 import javax.ejb.EJBException JavaDoc;
29 import javax.ejb.FinderException JavaDoc;
30
31 import org.apache.log4j.Logger;
32 import org.ejbca.core.ejb.JNDINames;
33 import org.ejbca.core.ejb.protect.TableProtectSessionLocal;
34 import org.ejbca.core.ejb.protect.TableProtectSessionLocalHome;
35 import org.ejbca.core.model.InternalResources;
36 import org.ejbca.core.model.ca.crl.RevokedCertInfo;
37 import org.ejbca.core.model.ca.store.CertificateInfo;
38 import org.ejbca.core.model.log.Admin;
39 import org.ejbca.core.model.log.LogEntry;
40 import org.ejbca.core.model.protect.TableVerifyResult;
41 import org.ejbca.util.CertTools;
42 import org.ejbca.util.JDBCUtil;
43 import org.ejbca.util.StringTools;
44
45 /** Common code between CertificateStoreSessionBean and CertificateStoreOnlyDataSessionBean
46  *
47  * @author lars
48  * @version $Id: CertificateDataUtil.java,v 1.10 2006/12/13 10:32:42 anatom Exp $
49  *
50  */

51 public class CertificateDataUtil {
52     /** Internal localization of logs and errors */
53     private static final InternalResources intres = InternalResources.getInstance();
54     
55     public interface Adapter {
56         void debug( String JavaDoc s );
57         void error( String JavaDoc s );
58         void error( String JavaDoc s, Exception JavaDoc e );
59         Logger getLogger();
60         void log(Admin admin, int caid, int module, Date JavaDoc time, String JavaDoc username,
61                  X509Certificate JavaDoc certificate, int event, String JavaDoc comment);
62     }
63     public static Certificate JavaDoc findCertificateByFingerprint(Admin admin, String JavaDoc fingerprint,
64                                                            CertificateDataLocalHome certHome,
65                                                            Adapter adapter) {
66         adapter.debug(">findCertificateByFingerprint()");
67         Certificate JavaDoc ret = null;
68
69         try {
70             CertificateDataLocal res = certHome.findByPrimaryKey(new CertificateDataPK(fingerprint));
71             ret = res.getCertificate();
72             adapter.debug("<findCertificateByFingerprint()");
73         } catch (FinderException JavaDoc fe) {
74             // Return null;
75
} catch (Exception JavaDoc e) {
76             adapter.getLogger().error("Error finding certificate with fp: " + fingerprint);
77             throw new EJBException JavaDoc(e);
78         }
79         return ret;
80     } // findCertificateByFingerprint
81

82     public static Certificate JavaDoc findCertificateByIssuerAndSerno(Admin admin, String JavaDoc issuerDN, BigInteger JavaDoc serno, CertificateDataLocalHome certHome, Adapter adapter) {
83         if (adapter.getLogger().isDebugEnabled()) {
84             adapter.debug(">findCertificateByIssuerAndSerno(), dn:" + issuerDN + ", serno=" + serno);
85         }
86         // First make a DN in our well-known format
87
String JavaDoc dn = CertTools.stringToBCDNString(issuerDN);
88         dn = StringTools.strip(dn);
89         if (adapter.getLogger().isDebugEnabled()) {
90             adapter.debug("Looking for cert with (transformed)DN: " + dn);
91         }
92         try {
93             Collection JavaDoc coll = certHome.findByIssuerDNSerialNumber(dn, serno.toString());
94             Certificate JavaDoc ret = null;
95             if (coll != null) {
96                 if (coll.size() > 1)
97                     adapter.log(admin, issuerDN.hashCode(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_DATABASE, "Error in database, more than one certificate has the same Issuer : " + issuerDN + " and serialnumber "
98                             + serno.toString(16) + ".");
99                 Iterator JavaDoc iter = coll.iterator();
100                 if (iter.hasNext()) {
101                     ret = ((CertificateDataLocal) iter.next()).getCertificate();
102                 }
103             }
104             if (adapter.getLogger().isDebugEnabled()) {
105                 adapter.debug("<findCertificateByIssuerAndSerno(), dn:" + issuerDN + ", serno=" + serno);
106             }
107             return ret;
108         } catch (Exception JavaDoc fe) {
109             throw new EJBException JavaDoc(fe);
110         }
111     } //findCertificateByIssuerAndSerno
112

113     public static Collection JavaDoc findCertificatesByType(Admin admin, int type, String JavaDoc issuerDN,
114                                                     CertificateDataLocalHome certHome,
115                                                     Adapter adapter) {
116         adapter.debug(">findCertificatesByType()");
117         if (null == admin
118                 || type <= 0
119                 || type > CertificateDataBean.CERTTYPE_SUBCA + CertificateDataBean.CERTTYPE_ENDENTITY + CertificateDataBean.CERTTYPE_ROOTCA) {
120             throw new IllegalArgumentException JavaDoc();
121         }
122         StringBuffer JavaDoc ctypes = new StringBuffer JavaDoc();
123         if ((type & CertificateDataBean.CERTTYPE_SUBCA) > 0) {
124             ctypes.append(CertificateDataBean.CERTTYPE_SUBCA);
125         }
126         if ((type & CertificateDataBean.CERTTYPE_ENDENTITY) > 0) {
127             if (ctypes.length() > 0) {
128                 ctypes.append(", ");
129             }
130             ctypes.append(CertificateDataBean.CERTTYPE_ENDENTITY);
131         }
132         if ((type & CertificateDataBean.CERTTYPE_ROOTCA) > 0) {
133             if (ctypes.length() > 0) {
134                 ctypes.append(", ");
135             }
136             ctypes.append(CertificateDataBean.CERTTYPE_ROOTCA);
137         }
138
139         Connection JavaDoc con = null;
140         PreparedStatement JavaDoc ps = null;
141         ResultSet JavaDoc result = null;
142         try {
143             ArrayList JavaDoc vect;
144             // Status 20 = CertificateDataBean.CERT_ACTIVE
145
StringBuffer JavaDoc stmt = new StringBuffer JavaDoc("SELECT DISTINCT fingerprint FROM CertificateData WHERE status = "+CertificateDataBean.CERT_ACTIVE+" AND ");
146             stmt.append(" type IN (");
147             stmt.append(ctypes.toString());
148             stmt.append(')');
149             if (null != issuerDN && issuerDN.length() > 0) {
150                 String JavaDoc dn = CertTools.stringToBCDNString(issuerDN);
151                 dn = StringTools.strip(dn);
152                 if (adapter.getLogger().isDebugEnabled()) {
153                     adapter.debug("findCertificatesByType() : Looking for cert with (transformed)DN: " + dn);
154                 }
155                 stmt.append(" AND issuerDN = '");
156                 stmt.append(dn);
157                 stmt.append('\'');
158             }
159             if (adapter.getLogger().isDebugEnabled()) {
160                 adapter.debug("findCertificatesByType() : executing SQL statement\n"
161                         + stmt.toString());
162             }
163             con = JDBCUtil.getDBConnection(JNDINames.DATASOURCE);
164             ps = con.prepareStatement(stmt.toString());
165             result = ps.executeQuery();
166
167             vect = new ArrayList JavaDoc();
168             while (result.next()) {
169                 Certificate JavaDoc cert = findCertificateByFingerprint(admin, result.getString(1),
170                                                                 certHome, adapter);
171                 if (cert != null) {
172                     vect.add(cert);
173                 }
174             }
175
176             adapter.debug("<findCertificatesByType()");
177             return vect;
178         } catch (Exception JavaDoc e) {
179             throw new EJBException JavaDoc(e);
180         } finally {
181             JDBCUtil.close(con, ps, result);
182         }
183     } // findCertificatesByType
184

185     static public RevokedCertInfo isRevoked(Admin admin, String JavaDoc issuerDN, BigInteger JavaDoc serno,
186                                             CertificateDataLocalHome certHome, TableProtectSessionLocalHome protectHome, Adapter adapter) {
187         if (adapter.getLogger().isDebugEnabled()) {
188             adapter.debug(">isRevoked(), dn:" + issuerDN + ", serno=" + serno.toString(16));
189         }
190         // First make a DN in our well-known format
191
String JavaDoc dn = CertTools.stringToBCDNString(issuerDN);
192
193         try {
194             Collection JavaDoc coll = certHome.findByIssuerDNSerialNumber(dn, serno.toString());
195             if (coll != null) {
196                 if (coll.size() > 1) {
197                     String JavaDoc msg = intres.getLocalizedMessage("store.errorseveralissuerserno", issuerDN, serno.toString(16));
198                     adapter.log(admin, issuerDN.hashCode(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(),
199                                 null, null, LogEntry.EVENT_ERROR_DATABASE, msg);
200                 }
201                 Iterator JavaDoc iter = coll.iterator();
202                 if (iter.hasNext()) {
203                     RevokedCertInfo revinfo = null;
204                     CertificateDataLocal data = (CertificateDataLocal) iter.next();
205                     if (protectHome != null) {
206                         CertificateInfo entry = new CertificateInfo(data.getFingerprint(), data.getCaFingerprint(), data.getSerialNumber(), data.getIssuerDN(), data.getSubjectDN(), data.getStatus(), data.getType(), data.getExpireDate(), data.getRevocationDate(), data.getRevocationReason());
207                         TableProtectSessionLocal protect;
208                         try {
209                             protect = protectHome.create();
210                             // The verify method will log failed verifies itself
211
TableVerifyResult res = protect.verify(entry);
212                             if (res.getResultCode() != TableVerifyResult.VERIFY_SUCCESS) {
213                                 //adapter.error("Verify failed, but we go on anyway.");
214
}
215                         } catch (CreateException JavaDoc e) {
216                             String JavaDoc msg = intres.getLocalizedMessage("protect.errorcreatesession");
217                             adapter.error(msg, e);
218                         }
219                     }
220                     revinfo = new RevokedCertInfo(serno, new Date JavaDoc(data.getRevocationDate()), data.getRevocationReason());
221                     // Make sure we have it as NOT revoked if it isn't
222
if (data.getStatus() != CertificateDataBean.CERT_REVOKED) {
223                         revinfo.setReason(RevokedCertInfo.NOT_REVOKED);
224                     }
225                     if (adapter.getLogger().isDebugEnabled()) {
226                         adapter.debug("<isRevoked() returned " + ((data.getStatus() == CertificateDataBean.CERT_REVOKED) ? "yes" : "no"));
227                     }
228                     return revinfo;
229                 }
230             }
231             if (adapter.getLogger().isDebugEnabled()) {
232                 adapter.debug("<isRevoked() did not find certificate with dn "+dn+" and serno "+serno.toString(16));
233             }
234         } catch (Exception JavaDoc e) {
235             throw new EJBException JavaDoc(e);
236         }
237         return null;
238     } //isRevoked
239
}
240
Popular Tags