KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > se > anatom > ejbca > ca > store > TestCertificateRetrival


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 se.anatom.ejbca.ca.store;
15
16 import java.math.BigInteger JavaDoc;
17 import java.security.cert.X509Certificate JavaDoc;
18 import java.util.ArrayList JavaDoc;
19 import java.util.Collection JavaDoc;
20 import java.util.HashSet JavaDoc;
21 import java.util.Iterator JavaDoc;
22 import java.util.Vector JavaDoc;
23
24 import javax.naming.Context JavaDoc;
25 import javax.naming.NamingException JavaDoc;
26
27 import junit.framework.TestCase;
28
29 import org.apache.log4j.Logger;
30 import org.ejbca.core.ejb.ca.store.CertificateDataBean;
31 import org.ejbca.core.ejb.ca.store.ICertificateStoreSessionHome;
32 import org.ejbca.core.ejb.ca.store.ICertificateStoreSessionRemote;
33 import org.ejbca.core.model.ca.crl.RevokedCertInfo;
34 import org.ejbca.core.model.log.Admin;
35 import org.ejbca.util.Base64;
36 import org.ejbca.util.CertTools;
37
38 /**
39  * @version $Id: TestCertificateRetrival.java,v 1.8 2006/08/06 12:38:09 anatom Exp $
40  */

41 public class TestCertificateRetrival extends TestCase {
42
43     static byte[] testrootcert = Base64.decode(("MIICnTCCAgagAwIBAgIBADANBgkqhkiG9w0BAQQFADBEMQswCQYDVQQGEwJTRTET"
44             + "MBEGA1UECBMKU29tZS1TdGF0ZTEPMA0GA1UEChMGQW5hdG9tMQ8wDQYDVQQDEwZU"
45             + "ZXN0Q0EwHhcNMDMwODIxMTcyMzAyWhcNMTMwNTIwMTcyMzAyWjBEMQswCQYDVQQG"
46             + "EwJTRTETMBEGA1UECBMKU29tZS1TdGF0ZTEPMA0GA1UEChMGQW5hdG9tMQ8wDQYD"
47             + "VQQDEwZUZXN0Q0EwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMoSn6W9BU6G"
48             + "BLoasmAZ56uuOVV0pspyuPrPVtuNjEiJqwNr6S7Xa3+MoMq/bhogfml8YuU320o3"
49             + "CWKB4n6kcRMiRZkhWtSL6HlO9MtE5Gq1NT1WrjkMefOYA501//U0LxLerPa8YLlD"
50             + "CvT6GCY+B1KA8fo2GMditEfVL2uEJZpDAgMBAAGjgZ4wgZswHQYDVR0OBBYEFGU3"
51             + "qE54h3lFUuQI+TGLRT798DhlMGwGA1UdIwRlMGOAFGU3qE54h3lFUuQI+TGLRT79"
52             + "8DhloUikRjBEMQswCQYDVQQGEwJTRTETMBEGA1UECBMKU29tZS1TdGF0ZTEPMA0G"
53             + "A1UEChMGQW5hdG9tMQ8wDQYDVQQDEwZUZXN0Q0GCAQAwDAYDVR0TBAUwAwEB/zAN"
54             + "BgkqhkiG9w0BAQQFAAOBgQCn9g0SR06RTLFXN0zABYIVHe1+N1n3DcrOIrySg2h1"
55             + "fIUV9fB9KsPp9zbLkoL2+UmnXsK8kCH0Tc7WaV0xXKrjtMxN6XIc431WS51QGW+B"
56             + "X4XyXWbKwiJEadp6QZWCHhuXhYZnUNry3uVRWHj465P2OYlYH0rOtA2TVAl8ox5R"
57             + "iQ==").getBytes());
58
59     static byte[] testcacert = Base64.decode(("MIIB/zCCAWgCAQMwDQYJKoZIhvcNAQEEBQAwRDELMAkGA1UEBhMCU0UxEzARBgNV"
60             + "BAgTClNvbWUtU3RhdGUxDzANBgNVBAoTBkFuYXRvbTEPMA0GA1UEAxMGVGVzdENB"
61             + "MB4XDTAzMDkyMjA5MTExNVoXDTEzMDQyMjA5MTExNVowTDELMAkGA1UEBhMCU0Ux"
62             + "EzARBgNVBAgTClNvbWUtU3RhdGUxDzANBgNVBAoTBkFuYXRvbTEXMBUGA1UEAxMO"
63             + "U3Vib3JkaW5hdGUgQ0EwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALATItEt"
64             + "JrFmMswJRBxwhc8T8MXGrTGmovLCRIYmgX/0cklcK0pM7pDl63cX9Ps+3OsX90Ys"
65             + "d3v0YWVEULi3YThRnH3HJgB4W4QoALuBhcewzgpLePPhzyhn/YOqRIT/yY0tspCN"
66             + "AMLdu+Iqn/j20sFwva1NyLoA6sH28o/Jmf5zAgMBAAEwDQYJKoZIhvcNAQEEBQAD"
67             + "gYEAMBTTmQl6axoNsMflQOzCkZPqk30Z9yltdMMT7Q1tCQDjbOiBs6tS/3au5DSZ"
68             + "Xf9SBoWysdxNVHdYOIT5dkqJtCjC6nGiqnj5NZDXDUZ/4++NPlTEULy6ECszv2i7"
69             + "NQ3q4x7h0mgUMaCA7sayQmLe/eOcwYxpGk2x0y5hrHJmcao=").getBytes());
70
71     static byte[] testcert = Base64.decode(("MIICBDCCAW0CAQMwDQYJKoZIhvcNAQEEBQAwTDELMAkGA1UEBhMCU0UxEzARBgNV"
72             + "BAgTClNvbWUtU3RhdGUxDzANBgNVBAoTBkFuYXRvbTEXMBUGA1UEAxMOU3Vib3Jk"
73             + "aW5hdGUgQ0EwHhcNMDMwOTIyMDkxNTEzWhcNMTMwNDIyMDkxNTEzWjBJMQswCQYD"
74             + "VQQGEwJTRTETMBEGA1UECBMKU29tZS1TdGF0ZTEPMA0GA1UEChMGQW5hdG9tMRQw"
75             + "EgYDVQQDEwtGb29CYXIgVXNlcjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA"
76             + "xPpmVYVBzlGJxUfZa6IsHsk+HrMTbHWr/EUkiZIam95t+0SIFZHUers2PIv+GWVp"
77             + "TmH/FTXNWVWw+W6bFlb17rfbatAkVfAYuBGRh+nUS/CPTPNw1jDeCuZRweD+DCNr"
78             + "icx/svv0Hi/9scUqrADwtO2O7oBy7Lb/Vfa6BOnBdiECAwEAATANBgkqhkiG9w0B"
79             + "AQQFAAOBgQAo5RzuUkLdHdAyJIG2IRptIJDOa0xq8eH2Duw9Xa3ieI9+ogCNaqWy"
80             + "V5Oqx2lLsdn9CXxAwT/AsqwZ0ZFOJY1V2BgLTPH+vxnPOm0Xu61fl2XLtRBAycva"
81             + "9iknwKZ3PCILvA5qjL9VedxiFhcG/p83SnPOrIOdsHykMTvO8/j8mA==").getBytes());
82
83     private static Logger m_log = Logger.getLogger(TestCertificateRetrival.class);
84
85     private Context JavaDoc m_ctx;
86     private ICertificateStoreSessionHome m_storehome;
87     private HashSet JavaDoc m_certs;
88     private HashSet JavaDoc m_certfps;
89     private String JavaDoc rootCaFp = null;
90     private String JavaDoc subCaFp = null;
91     private String JavaDoc endEntityFp = null;
92     private Admin admin;
93
94     private static void dumpCertificates(Collection JavaDoc certs) {
95         m_log.debug(">dumpCertificates()");
96         if (null != certs && !certs.isEmpty()) {
97             Iterator JavaDoc iter = certs.iterator();
98
99             while (iter.hasNext()) {
100                 Object JavaDoc obj = iter.next();
101                 if (obj instanceof X509Certificate JavaDoc) {
102                     m_log.debug("***** X509Certificate");
103                     m_log.debug(" SubjectDN : "
104                             + ((X509Certificate JavaDoc) obj).getSubjectDN());
105                     m_log.debug(" IssuerDN : "
106                             + ((X509Certificate JavaDoc) obj).getIssuerDN());
107                     //System.out.println(((X509Certificate) obj).getIssuerDN().getName()+";"+((X509Certificate) obj).getSerialNumber().toString(16)+";"+CertTools.getFingerprintAsString((X509Certificate) obj));
108
} else {
109                     m_log.warn("Object in collection is not a X509Certificate.");
110                 }
111             }
112         } else {
113             m_log.warn("Certificate collection is empty or NULL.");
114         }
115         m_log.debug("<dumpCertificates()");
116     }
117
118     public TestCertificateRetrival(String JavaDoc name) {
119         super(name);
120     }
121
122     private Context JavaDoc getInitialContext() throws NamingException JavaDoc {
123         m_log.debug(">getInitialContext");
124
125         Context JavaDoc ctx = new javax.naming.InitialContext JavaDoc();
126         m_log.debug("<getInitialContext");
127
128         return ctx;
129     }
130
131     protected void setUp() throws Exception JavaDoc {
132         m_log.debug(">setUp()");
133         CertTools.installBCProvider();
134
135         m_ctx = getInitialContext();
136
137         Object JavaDoc obj2 = m_ctx.lookup("CertificateStoreSession");
138         m_storehome = (ICertificateStoreSessionHome) javax.rmi.PortableRemoteObject.narrow(obj2,
139                 ICertificateStoreSessionHome.class);
140         ICertificateStoreSessionRemote store = m_storehome.create();
141         X509Certificate JavaDoc cert;
142         Admin adm = new Admin(Admin.TYPE_INTERNALUSER);
143         m_certs = new HashSet JavaDoc();
144         m_certfps = new HashSet JavaDoc();
145         cert = CertTools.getCertfromByteArray(testrootcert);
146         m_certs.add(cert);
147         m_certfps.add(CertTools.getFingerprintAsString(cert));
148         //System.out.println(cert.getIssuerDN().getName()+";"+cert.getSerialNumber().toString(16)+";"+CertTools.getFingerprintAsString(cert));
149
rootCaFp = CertTools.getFingerprintAsString(cert);
150         try {
151             if (store.findCertificateByFingerprint(adm, rootCaFp) == null) {
152                 store.storeCertificate(adm
153                         , cert
154                         , "o=AnaTom,c=SE"
155                         , rootCaFp
156                         , CertificateDataBean.CERT_ACTIVE
157                         , CertificateDataBean.CERTTYPE_ROOTCA);
158             }
159             cert = CertTools.getCertfromByteArray(testcacert);
160             m_certs.add(cert);
161             m_certfps.add(CertTools.getFingerprintAsString(cert));
162             //System.out.println(cert.getIssuerDN().getName()+";"+cert.getSerialNumber().toString(16)+";"+CertTools.getFingerprintAsString(cert));
163
subCaFp = CertTools.getFingerprintAsString(cert);
164             if (store.findCertificateByFingerprint(adm, subCaFp) == null) {
165                 store.storeCertificate(adm
166                         , cert
167                         , "o=AnaTom,c=SE"
168                         , subCaFp
169                         , CertificateDataBean.CERT_ACTIVE
170                         , CertificateDataBean.CERTTYPE_SUBCA);
171             }
172             cert = CertTools.getCertfromByteArray(testcert);
173             m_certs.add(cert);
174             m_certfps.add(CertTools.getFingerprintAsString(cert));
175             //System.out.println(cert.getIssuerDN().getName()+";"+cert.getSerialNumber().toString(16)+";"+CertTools.getFingerprintAsString(cert));
176
endEntityFp = CertTools.getFingerprintAsString(cert);
177             if (store.findCertificateByFingerprint(adm, endEntityFp) == null) {
178                 store.storeCertificate(adm
179                         , cert
180                         , "o=AnaTom,c=SE"
181                         , endEntityFp
182                         , CertificateDataBean.CERT_ACTIVE
183                         , CertificateDataBean.CERTTYPE_ENDENTITY);
184             }
185         } catch (Exception JavaDoc e) {
186             m_log.error("Error: ", e);
187             assertTrue("Error seting up tests: " + e.getMessage(), false);
188         }
189         admin = new Admin(Admin.TYPE_INTERNALUSER);
190         m_log.debug("<setUp()");
191     }
192
193     protected void tearDown() throws Exception JavaDoc {
194     }
195
196     public void test01AddCertificates() throws Exception JavaDoc {
197         m_log.debug(">test01AddCertificates()");
198         m_log.debug("<test01AddCertificates()");
199     }
200
201     /**
202      *
203      * @throws Exception error
204      */

205     public void test02FindCACertificates() throws Exception JavaDoc {
206         m_log.debug(">test02FindCACertificates()");
207         ICertificateStoreSessionRemote store = m_storehome.create();
208
209         // List all certificates to see
210
Collection JavaDoc certfps = store.findCertificatesByType(admin
211                 , CertificateDataBean.CERTTYPE_SUBCA
212                 , null);
213         assertNotNull("failed to list certs", certfps);
214         assertTrue("failed to list certs", certfps.size() != 0);
215
216         Iterator JavaDoc iter = certfps.iterator();
217         boolean found = false;
218         while (iter.hasNext()) {
219             Object JavaDoc obj = iter.next();
220             if (!(obj instanceof X509Certificate JavaDoc)) {
221                 assertTrue("method 'findCertificatesByType' does not return X509Certificate objects.\n"
222                         + "Class of returned object '" + obj.getClass().getName() + "'"
223                         , false);
224             }
225             X509Certificate JavaDoc cert = (X509Certificate JavaDoc)obj;
226             String JavaDoc fp = CertTools.getFingerprintAsString(cert);
227             if (fp.equals(subCaFp)) {
228                 found = true;
229             }
230         }
231         assertTrue(found);
232         m_log.debug("<test02FindCACertificates()");
233     }
234
235     /**
236      *
237      * @throws Exception error
238      */

239     public void test03FindEndEntityCertificates() throws Exception JavaDoc {
240         m_log.debug(">test03FindEndEntityCertificates()");
241
242         ICertificateStoreSessionRemote store = m_storehome.create();
243
244         // List all certificates to see, but only from our test certificates issuer, or we might get OutOfMemmory if there are plenty of certs
245
Collection JavaDoc certfps = store.findCertificatesByType(admin
246                 , CertificateDataBean.CERTTYPE_ENDENTITY
247                 , "CN=Subordinate CA,O=Anatom,ST=Some-State,C=SE");
248         assertNotNull("failed to list certs", certfps);
249         assertTrue("failed to list certs", certfps.size() != 0);
250
251         Iterator JavaDoc iter = certfps.iterator();
252         boolean found = false;
253         while (iter.hasNext()) {
254             Object JavaDoc obj = iter.next();
255             if (!(obj instanceof X509Certificate JavaDoc)) {
256                 assertTrue("method 'findCertificatesByType' does not return X509Certificate objects.\n"
257                         + "Class of returned object '" + obj.getClass().getName() + "'"
258                         , false);
259             }
260             X509Certificate JavaDoc cert = (X509Certificate JavaDoc)obj;
261             String JavaDoc fp = CertTools.getFingerprintAsString(cert);
262             if (fp.equals(endEntityFp)) {
263                 found = true;
264             }
265         }
266         assertTrue(found);
267
268         m_log.debug("<test03FindEndEntityCertificates()");
269     }
270
271     /**
272      *
273      * @throws Exception error
274      */

275     public void test04FindRootCertificates() throws Exception JavaDoc {
276         m_log.debug(">test04FindRootCertificates()");
277
278         ICertificateStoreSessionRemote store = m_storehome.create();
279
280         // List all certificates to see
281
Collection JavaDoc certfps = store.findCertificatesByType(admin
282                 , CertificateDataBean.CERTTYPE_ROOTCA
283                 , null);
284         assertNotNull("failed to list certs", certfps);
285         assertTrue("failed to list certs", certfps.size() != 0);
286
287         Iterator JavaDoc iter = certfps.iterator();
288         boolean found = false;
289         while (iter.hasNext()) {
290             Object JavaDoc obj = iter.next();
291             if (!(obj instanceof X509Certificate JavaDoc)) {
292                 assertTrue("method 'findCertificatesByType' does not return X509Certificate objects.\n"
293                         + "Class of returned object '" + obj.getClass().getName() + "'"
294                         , false);
295             }
296             X509Certificate JavaDoc cert = (X509Certificate JavaDoc)obj;
297             String JavaDoc fp = CertTools.getFingerprintAsString(cert);
298             if (fp.equals(rootCaFp)) {
299                 found = true;
300             }
301         }
302         assertTrue(found);
303
304         m_log.debug("<test04FindRootCertificates()");
305     }
306
307     /**
308      *
309      * @throws Exception error
310      */

311     public void test05CertificatesByIssuerAndSernos() throws Exception JavaDoc {
312         m_log.debug(">test05CertificatesByIssuerAndSernos()");
313         ICertificateStoreSessionRemote store = m_storehome.create();
314         X509Certificate JavaDoc rootcacert;
315         X509Certificate JavaDoc subcacert;
316         X509Certificate JavaDoc cert;
317         Vector JavaDoc sernos;
318         Collection JavaDoc certfps;
319
320         rootcacert = CertTools.getCertfromByteArray(testrootcert);
321         subcacert = CertTools.getCertfromByteArray(testcacert);
322         cert = CertTools.getCertfromByteArray(testcert);
323
324         sernos = new Vector JavaDoc();
325         sernos.add(subcacert.getSerialNumber());
326         sernos.add(rootcacert.getSerialNumber());
327         certfps = store.findCertificatesByIssuerAndSernos(admin
328                 , rootcacert.getSubjectDN().getName()
329                 , sernos);
330         assertNotNull("failed to list certs", certfps);
331         // we expect two certificates cause the rootca certificate is
332
// self signed and so the issuer is identical with the subject
333
// to which the certificate belongs
334
dumpCertificates(certfps);
335         assertTrue("failed to list certs", certfps.size() == 2);
336
337         sernos = new Vector JavaDoc();
338         sernos.add(cert.getSerialNumber());
339         certfps = store.findCertificatesByIssuerAndSernos(admin
340                 , subcacert.getSubjectDN().getName()
341                 , sernos);
342         assertNotNull("failed to list certs", certfps);
343         dumpCertificates(certfps);
344         assertTrue("failed to list certs", certfps.size() == 1);
345         assertTrue("Unable to find test certificate."
346                 , m_certfps.contains(CertTools.getFingerprintAsString((X509Certificate JavaDoc)certfps.iterator().next())));
347         m_log.debug("<test05CertificatesByIssuerAndSernos()");
348     }
349
350     /**
351      *
352      * @throws Exception error
353      */

354     /* Don't run this test since it can lookup a looot of certs and you will get an OutOfMemoryException
355     public void test06RetriveAllCertificates() throws Exception {
356         m_log.debug(">test06CertificatesByIssuer()");
357         ICertificateStoreSessionRemote store = m_storehome.create();
358
359         // List all certificates to see
360         Collection certfps = store.findCertificatesByType(admin
361                 , CertificateDataBean.CERTTYPE_ROOTCA + CertificateDataBean.CERTTYPE_SUBCA + CertificateDataBean.CERTTYPE_ENDENTITY
362                 , null);
363         assertNotNull("failed to list certs", certfps);
364         assertTrue("failed to list certs", certfps.size() >= 2);
365         // Iterate over m_certs to see that we found all our certs (we probably found alot more...)
366         Iterator iter = m_certs.iterator();
367         while (iter.hasNext()) {
368             assertTrue("Unable to find all test certificates.", certfps.contains(iter.next()));
369         }
370         m_log.debug("<test06CertificatesByIssuer()");
371     } */

372
373     /**
374      *
375      * @throws Exception error
376      */

377     public void test07FindCACertificatesWithIssuer() throws Exception JavaDoc {
378         m_log.debug(">test07FindCACertificatesWithIssuer()");
379
380         ICertificateStoreSessionRemote store = m_storehome.create();
381         X509Certificate JavaDoc rootcacert = CertTools.getCertfromByteArray(testrootcert);
382
383         // List all certificates to see
384
Collection JavaDoc certfps = store.findCertificatesByType(admin
385                 , CertificateDataBean.CERTTYPE_SUBCA
386                 , rootcacert.getSubjectDN().getName());
387         assertNotNull("failed to list certs", certfps);
388         assertTrue("failed to list certs", certfps.size() >= 1);
389         Iterator JavaDoc iter = certfps.iterator();
390         boolean found = false;
391         while (iter.hasNext()) {
392             X509Certificate JavaDoc cert = (X509Certificate JavaDoc) iter.next();
393             if (subCaFp.equals(CertTools.getFingerprintAsString(cert))) {
394                 found = true;
395             }
396         }
397         assertTrue("Unable to find all test certificates.", found);
398         m_log.debug("<test07FindCACertificatesWithIssuer()");
399     }
400
401     /**
402      *
403      * @throws Exception error
404      */

405     public void test08LoadRevocationInfo() throws Exception JavaDoc {
406         m_log.debug(">test08LoadRevocationInfo()");
407
408         ArrayList JavaDoc revstats = new ArrayList JavaDoc();
409         X509Certificate JavaDoc rootcacert;
410         X509Certificate JavaDoc subcacert;
411         ICertificateStoreSessionRemote store = m_storehome.create();
412
413         ArrayList JavaDoc sernos = new ArrayList JavaDoc();
414         rootcacert = CertTools.getCertfromByteArray(testrootcert);
415         subcacert = CertTools.getCertfromByteArray(testcacert);
416         sernos.add(rootcacert.getSerialNumber());
417         sernos.add(subcacert.getSerialNumber());
418
419         Iterator JavaDoc iter = sernos.iterator();
420         while (iter.hasNext()) {
421             BigInteger JavaDoc bi = (BigInteger JavaDoc)iter.next();
422             RevokedCertInfo rev = store.isRevoked(admin
423                     , rootcacert.getSubjectDN().getName()
424                     , bi);
425             revstats.add(rev);
426         }
427
428         assertNotNull("Unable to retrive certificate revocation status.", revstats);
429         assertTrue("Method 'isRevoked' does not return status for ALL certificates.", revstats.size() >= 2);
430
431         iter = revstats.iterator();
432         while (iter.hasNext()) {
433             RevokedCertInfo rci = (RevokedCertInfo) iter.next();
434             m_log.debug("Certificate revocation information:\n"
435                     + " Serialnumber : " + rci.getUserCertificate().toString() + "\n"
436                     + " Revocation date : " + rci.getRevocationDate().toString() + "\n"
437                     + " Revocation reason : " + rci.getReason() + "\n");
438         }
439         m_log.debug("<test08LoadRevocationInfo()");
440     }
441 }
Popular Tags