KickJava   Java API By Example, From Geeks To Geeks.

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


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.rmi.RemoteException JavaDoc;
17 import java.security.KeyPair JavaDoc;
18 import java.security.cert.Certificate JavaDoc;
19 import java.security.cert.X509Certificate JavaDoc;
20 import java.util.Collection JavaDoc;
21 import java.util.Date JavaDoc;
22 import java.util.Iterator JavaDoc;
23 import java.util.Random JavaDoc;
24
25 import javax.naming.Context JavaDoc;
26 import javax.naming.NamingException JavaDoc;
27
28 import junit.framework.TestCase;
29
30 import org.apache.log4j.Logger;
31 import org.ejbca.core.ejb.ca.store.CertificateDataBean;
32 import org.ejbca.core.ejb.ca.store.ICertificateStoreSessionHome;
33 import org.ejbca.core.ejb.ca.store.ICertificateStoreSessionRemote;
34 import org.ejbca.core.model.SecConst;
35 import org.ejbca.core.model.ca.catoken.CATokenConstants;
36 import org.ejbca.core.model.ca.catoken.CATokenInfo;
37 import org.ejbca.core.model.ca.crl.RevokedCertInfo;
38 import org.ejbca.core.model.ca.store.CertReqHistory;
39 import org.ejbca.core.model.ca.store.CertificateInfo;
40 import org.ejbca.core.model.log.Admin;
41 import org.ejbca.core.model.ra.UserDataVO;
42 import org.ejbca.util.CertTools;
43 import org.ejbca.util.KeyTools;
44
45
46
47
48 /**
49  * Tests certificate store.
50  *
51  * @version $Id: TestCertificateData.java,v 1.9 2006/10/31 08:24:53 anatom Exp $
52  */

53 public class TestCertificateData extends TestCase {
54
55     private static Logger log = Logger.getLogger(TestCertificateData.class);
56     private static Context JavaDoc ctx;
57     private static ICertificateStoreSessionHome storehome;
58     private static X509Certificate JavaDoc cert;
59     private static X509Certificate JavaDoc cert1;
60     private static X509Certificate JavaDoc cert2;
61     private static String JavaDoc username = "";
62     private static Admin admin = null;
63     private static KeyPair JavaDoc keyPair;
64
65     /**
66      * Creates a new TestCertificateData object.
67      *
68      * @param name name
69      */

70     public TestCertificateData(String JavaDoc name) {
71         super(name);
72     }
73
74     protected void setUp() throws Exception JavaDoc {
75         log.debug(">setUp()");
76         CertTools.installBCProvider();
77
78         admin = new Admin(Admin.TYPE_INTERNALUSER);
79         ctx = getInitialContext();
80         Object JavaDoc obj2 = ctx.lookup("CertificateStoreSession");
81         storehome = (ICertificateStoreSessionHome) javax.rmi.PortableRemoteObject.narrow(obj2, ICertificateStoreSessionHome.class);
82         
83         log.debug("<setUp()");
84     }
85
86     protected void tearDown() throws Exception JavaDoc {
87     }
88
89     private Context JavaDoc getInitialContext() throws NamingException JavaDoc {
90         log.debug(">getInitialContext");
91         Context JavaDoc ctx = new javax.naming.InitialContext JavaDoc();
92         log.debug("<getInitialContext");
93         return ctx;
94     }
95
96     /**
97      * creates new certs
98      *
99      * @throws Exception error
100      */

101     public void test01CreateNewCertRSASha1() throws Exception JavaDoc {
102         log.debug(">test01CreateNewCert()");
103         // create a key pair and a new self signed certificate
104
log.info("Generating a small key pair, might take a few seconds...");
105         keyPair = KeyTools.genKeys("512", CATokenConstants.KEYALGORITHM_RSA);
106         cert = CertTools.genSelfCert("C=SE,O=PrimeCA,OU=TestCertificateData,CN=MyNameIsFoo", 24, null, keyPair.getPrivate(), keyPair.getPublic(), CATokenInfo.SIGALG_SHA1_WITH_RSA, false);
107         String JavaDoc fp = CertTools.getFingerprintAsString(cert);
108
109         ICertificateStoreSessionRemote store = storehome.create();
110         try {
111             Certificate JavaDoc ce = store.findCertificateByFingerprint(admin,fp);
112             if (ce != null) {
113                 assertTrue("Certificate with fp="+fp+" already exists in db, very strange since I just generated it.", false);
114             }
115             boolean ret = store.storeCertificate(admin, cert, "foo", "1234", CertificateDataBean.CERT_INACTIVE, CertificateDataBean.CERT_TYPE_ENCRYPTION);
116             //log.info("Stored new cert with fp="+fp);
117
assertTrue("Failed to store", ret);
118             log.debug("stored it!");
119         } catch (RemoteException JavaDoc e) {
120             log.error("Error storing certificate: ",e);
121             assertTrue("Error storing certificate.", false);
122             return;
123         }
124         log.debug("<test01CreateNewCert()");
125     }
126
127     /**
128      * finds and alters certificates
129      *
130      * @throws Exception error
131      */

132     public void test02FindAndChange() throws Exception JavaDoc {
133         log.debug(">test02FindAndChange()");
134         String JavaDoc fp = CertTools.getFingerprintAsString(cert);
135         ICertificateStoreSessionRemote store = storehome.create();
136         try {
137             X509Certificate JavaDoc ce = (X509Certificate JavaDoc)store.findCertificateByFingerprint(admin,fp);
138             assertNotNull("Cannot find certificate with fp="+fp,ce);
139             CertificateInfo info = store.getCertificateInfo(admin, fp);
140             //log.info("Got certificate info for cert with fp="+fp);
141
assertEquals("fingerprint does not match.",fp,info.getFingerprint());
142             assertEquals("CAfingerprint does not match.","1234",info.getCAFingerprint());
143             assertEquals("serialnumber does not match.",ce.getSerialNumber(),info.getSerialNumber());
144             assertEquals("issuerdn does not match.",CertTools.getIssuerDN(ce),info.getIssuerDN());
145             assertEquals("subjectdn does not match.",CertTools.getSubjectDN(ce),info.getSubjectDN());
146             // The cert was just stored above with status INACTIVE
147
assertEquals("status does not match.",CertificateDataBean.CERT_INACTIVE,info.getStatus());
148             assertEquals("type does not match.",CertificateDataBean.CERT_TYPE_ENCRYPTION,info.getType());
149             assertEquals("exiredate does not match.",ce.getNotAfter(),info.getExpireDate());
150             // We just stored it above, not revoked
151
assertEquals("revocation reason does not match.",RevokedCertInfo.NOT_REVOKED,info.getRevocationReason());
152             log.info("revocationdate (before rev)=" + info.getRevocationDate());
153             store.revokeCertificate(admin,ce,null,RevokedCertInfo.REVOKATION_REASON_KEYCOMPROMISE);
154             CertificateInfo info1 = store.getCertificateInfo(admin, fp);
155             assertEquals("revocation reason does not match.",RevokedCertInfo.REVOKATION_REASON_KEYCOMPROMISE,info1.getRevocationReason());
156             log.info("revocationdate (after rev)=" + info1.getRevocationDate());
157             assertTrue("Revocation date in future.", new Date JavaDoc().compareTo(info1.getRevocationDate())>=0);
158         } catch (RemoteException JavaDoc e) {
159             log.error("Error getting or revoking certificate: ",e);
160             assertTrue("Error getting or revoking certificate.", false);
161             return;
162         }
163         log.debug("<test02FindAndChange()");
164     }
165
166     /**
167      * listst and revokes certs
168      *
169      * @throws Exception error
170      */

171     public void test03listAndRevoke() throws Exception JavaDoc {
172         log.debug(">test03listAndRevoke()");
173         ICertificateStoreSessionRemote store = storehome.create();
174         String JavaDoc issuerDN = CertTools.getIssuerDN(cert);
175         String JavaDoc subjectDN = CertTools.getSubjectDN(cert);
176         // List all certificates to see
177
Collection JavaDoc certfps = store.listAllCertificates(admin, issuerDN);
178         assertNotNull("failed to list certs", certfps);
179         assertTrue("failed to list certs", certfps.size() != 0);
180
181         int size = certfps.size();
182         log.debug("List certs: " + size);
183
184         // List all certificates for user foo, which we have created in TestSignSession
185
certfps = store.findCertificatesBySubjectAndIssuer(new Admin(Admin.TYPE_INTERNALUSER), subjectDN, issuerDN);
186         assertTrue("something weird with size, all < foos", size >= certfps.size());
187         log.debug("List certs for foo: " + certfps.size());
188         Iterator JavaDoc iter = certfps.iterator();
189         while (iter.hasNext()) {
190             X509Certificate JavaDoc cert = (X509Certificate JavaDoc) iter.next();
191             String JavaDoc fp = CertTools.getFingerprintAsString(cert);
192             log.debug("revoking cert with fp="+fp);
193             // Revoke all foos certificates, note that revokeCertificate will not change status of certificates that are already revoked
194
store.revokeCertificate(admin, cert, null, RevokedCertInfo.REVOKATION_REASON_AFFILIATIONCHANGED);
195             log.debug("Revoked cert " + fp);
196         }
197         log.debug("<test03listAndRevoke()");
198     }
199
200     /**
201      * checks revoked certs
202      *
203      * @throws Exception error
204      */

205     public void test04CheckRevoked() throws Exception JavaDoc {
206         log.debug(">test04CheckRevoked()");
207
208         ICertificateStoreSessionRemote store = storehome.create();
209         String JavaDoc issuerDN = CertTools.getIssuerDN(cert);
210         String JavaDoc subjectDN = CertTools.getSubjectDN(cert);
211         // List all certificates for user foo, which we have created in TestSignSession
212
Collection JavaDoc certfps = store.findCertificatesBySubjectAndIssuer(new Admin(Admin.TYPE_INTERNALUSER), subjectDN, issuerDN);
213         assertNotNull("failed to list certs", certfps);
214         assertTrue("failed to list certs", certfps.size() != 0);
215
216         // Verify that cert are revoked
217
Iterator JavaDoc iter = certfps.iterator();
218         while (iter.hasNext()) {
219             X509Certificate JavaDoc cert = (X509Certificate JavaDoc) iter.next();
220             String JavaDoc fp = CertTools.getFingerprintAsString(cert);
221             CertificateInfo rev = store.getCertificateInfo(admin, fp);
222             log.info("revocationdate (after rev)=" + rev.getRevocationDate());
223             assertTrue("Revocation date in future.", new Date JavaDoc().compareTo(rev.getRevocationDate())>=0);
224             assertTrue(rev.getStatus() == CertificateDataBean.CERT_REVOKED);
225         }
226
227         log.debug("<test04CheckRevoked()");
228     }
229
230     /**
231      * finds certificates again
232      *
233      * @throws Exception error
234      */

235     public void test05FindAgain() throws Exception JavaDoc {
236         log.debug(">test05FindAgain()");
237
238         String JavaDoc fp = CertTools.getFingerprintAsString(cert);
239
240         ICertificateStoreSessionRemote store = storehome.create();
241         CertificateInfo data3 = store.getCertificateInfo(admin, fp);
242         assertNotNull("Failed to find cert", data3);
243         log.debug("found by key! =" + data3);
244         log.debug("fp=" + data3.getFingerprint());
245         log.debug("issuer=" + data3.getIssuerDN());
246         log.debug("subject=" + data3.getSubjectDN());
247         log.debug("cafp=" + data3.getCAFingerprint());
248         assertNotNull("wrong CAFingerprint", data3.getCAFingerprint());
249         log.debug("status=" + data3.getStatus());
250         assertTrue("wrong status", data3.getStatus() == CertificateDataBean.CERT_REVOKED);
251         log.debug("type=" + data3.getType());
252         assertTrue("wrong type", (data3.getType() & SecConst.USER_ENDUSER) == SecConst.USER_ENDUSER);
253         log.debug("serno=" + data3.getSerialNumber());
254         log.debug("expiredate=" + data3.getExpireDate());
255         log.debug("revocationdate=" + data3.getRevocationDate());
256         log.debug("revocationreason=" + data3.getRevocationReason());
257         assertEquals("Wrong revocation reason", data3.getRevocationReason(), RevokedCertInfo.REVOKATION_REASON_KEYCOMPROMISE);
258
259         log.debug("Looking for cert with DN=" + CertTools.getSubjectDN(cert));
260         Collection JavaDoc certs = store.findCertificatesBySubjectAndIssuer(new Admin(Admin.TYPE_INTERNALUSER), CertTools.getSubjectDN(cert), CertTools.getIssuerDN(cert));
261         Iterator JavaDoc iter = certs.iterator();
262         while (iter.hasNext()) {
263             X509Certificate JavaDoc xcert = (X509Certificate JavaDoc) iter.next();
264             log.debug(CertTools.getSubjectDN(xcert) + " - " + xcert.getSerialNumber().toString());
265             //log.debug(certs[i].toString());
266
}
267         log.debug("<test05FindAgain()");
268     }
269
270     /**
271      * finds certs by expire time
272      *
273      * @throws Exception error
274      */

275     public void test06FindByExpireTime() throws Exception JavaDoc {
276         log.debug(">test06FindByExpireTime()");
277
278         ICertificateStoreSessionRemote store = storehome.create();
279         String JavaDoc fp = CertTools.getFingerprintAsString(cert);
280
281         CertificateInfo data = store.getCertificateInfo(admin, fp);
282         assertNotNull("Failed to find cert", data);
283         log.debug("expiredate=" + data.getExpireDate());
284
285         // Seconds in a year
286
long yearmillis = 365 * 24 * 60 * 60 * 1000;
287         long findDateSecs = data.getExpireDate().getTime() - (yearmillis * 100);
288         Date JavaDoc findDate = new Date JavaDoc(findDateSecs);
289
290         log.info("1. Looking for cert with expireDate=" + findDate);
291
292         Collection JavaDoc certs = store.findCertificatesByExpireTime(new Admin(Admin.TYPE_INTERNALUSER), findDate);
293         log.debug("findCertificatesByExpireTime returned " + certs.size() + " certs.");
294         assertTrue("No certs should have expired before this date", certs.size() == 0);
295         findDateSecs = data.getExpireDate().getTime() + 10000;
296         findDate = new Date JavaDoc(findDateSecs);
297         log.info("2. Looking for cert with expireDate=" + findDate);
298         certs = store.findCertificatesByExpireTime(new Admin(Admin.TYPE_INTERNALUSER), findDate);
299         log.debug("findCertificatesByExpireTime returned " + certs.size() + " certs.");
300         assertTrue("Some certs should have expired before this date", certs.size() != 0);
301
302         Iterator JavaDoc iter = certs.iterator();
303
304         while (iter.hasNext()) {
305             X509Certificate JavaDoc cert = (X509Certificate JavaDoc) iter.next();
306             Date JavaDoc retDate = cert.getNotAfter();
307             log.debug(retDate);
308             assertTrue("This cert is not expired by the specified Date.", retDate.getTime() < findDate.getTime());
309         }
310
311         log.debug("<test06FindByExpireTime()");
312     }
313
314     /**
315      * finds certs by issuer and serialno
316      *
317      * @throws Exception error
318      */

319     public void test07FindByIssuerAndSerno() throws Exception JavaDoc {
320         log.debug(">test07FindByIssuerAndSerno()");
321
322         String JavaDoc issuerDN = CertTools.getIssuerDN(cert);
323         ICertificateStoreSessionRemote store = storehome.create();
324         String JavaDoc fp = CertTools.getFingerprintAsString(cert);
325         CertificateInfo data3 = store.getCertificateInfo(admin, fp);
326         assertNotNull("Failed to find cert", data3);
327
328         log.debug("Looking for cert with DN:" + CertTools.getIssuerDN(cert) + " and serno " + cert.getSerialNumber());
329         Certificate JavaDoc fcert = store.findCertificateByIssuerAndSerno(new Admin(Admin.TYPE_INTERNALUSER), issuerDN, cert.getSerialNumber());
330         assertNotNull("Cant find by issuer and serno", fcert);
331
332         //log.debug(fcert.toString());
333
log.debug("<test07FindByIssuerAndSerno()");
334     }
335
336     /**
337      * checks if a certificate is revoked
338      *
339      * @throws Exception error
340      */

341     public void test08IsRevoked() throws Exception JavaDoc {
342         log.debug(">test08IsRevoked()");
343         ICertificateStoreSessionRemote store = storehome.create();
344         String JavaDoc fp = CertTools.getFingerprintAsString(cert);
345         CertificateInfo data3 = store.getCertificateInfo(admin, fp);
346         assertNotNull("Failed to find cert", data3);
347         log.debug("found by key! =" + data3);
348         log.debug("fp=" + data3.getFingerprint());
349         log.debug("issuer=" + data3.getIssuerDN());
350         log.debug("subject=" + data3.getSubjectDN());
351         log.debug("cafp=" + data3.getCAFingerprint());
352         assertNotNull("wrong CAFingerprint", data3.getCAFingerprint());
353         log.debug("status=" + data3.getStatus());
354         assertTrue("wrong status", data3.getStatus() == CertificateDataBean.CERT_REVOKED);
355         log.debug("type=" + data3.getType());
356         assertTrue("wrong type", (data3.getType() == CertificateDataBean.CERTTYPE_ENDENTITY));
357         log.debug("serno=" + data3.getSerialNumber());
358         log.debug("expiredate=" + data3.getExpireDate());
359         log.debug("revocationdate=" + data3.getRevocationDate());
360         log.debug("revocationreason=" + data3.getRevocationReason());
361         assertEquals("wrong reason", data3.getRevocationReason(), RevokedCertInfo.REVOKATION_REASON_KEYCOMPROMISE);
362
363         log.debug("Checking if cert is revoked DN:'" + CertTools.getIssuerDN(cert) + "', serno:'" + cert.getSerialNumber().toString() + "'.");
364         RevokedCertInfo revinfo = store.isRevoked(new Admin(Admin.TYPE_INTERNALUSER), CertTools.getIssuerDN(cert), cert.getSerialNumber());
365         assertNotNull("Certificate not found, it should be!", revinfo);
366         int reason = revinfo.getReason();
367         assertEquals("Certificate not revoked, it should be!", RevokedCertInfo.REVOKATION_REASON_KEYCOMPROMISE, reason);
368         assertTrue("Wrong revocationDate!", revinfo.getRevocationDate().compareTo(data3.getRevocationDate()) == 0);
369         assertTrue("Wrong reason!", revinfo.getReason() == data3.getRevocationReason());
370         log.debug("Removed it!");
371         log.debug("<test08IsRevoked()");
372     }
373
374     /**
375      * Adds two certificate request histroy datas to the database.
376      *
377      * @throws Exception error
378      */

379     public void test09addCertReqHist() throws Exception JavaDoc {
380         log.debug(">test09addCertReqHist()");
381         ICertificateStoreSessionRemote store = storehome.create();
382                 
383         cert1 = CertTools.genSelfCert("C=SE,O=PrimeCA,OU=TestCertificateData,CN=CertReqHist1", 24, null, keyPair.getPrivate(), keyPair.getPublic(), CATokenInfo.SIGALG_SHA1_WITH_RSA, false);
384         cert2 = CertTools.genSelfCert("C=SE,O=PrimeCA,OU=TestCertificateData,CN=CertReqHist2", 24, null, keyPair.getPrivate(), keyPair.getPublic(), CATokenInfo.SIGALG_SHA1_WITH_RSA, false);
385         
386         UserDataVO userdata = new UserDataVO();
387         Random JavaDoc rand = new Random JavaDoc(new Date JavaDoc().getTime() + 4711);
388         for (int i = 0; i < 6; i++) {
389             int randint = rand.nextInt(9);
390             username += (new Integer JavaDoc(randint)).toString();
391         }
392         log.debug("Generated random username: username =" + username);
393         userdata.setUsername(username);
394         userdata.setDN("C=SE,O=PrimeCA,OU=TestCertificateData,CN=CertReqHist1");
395         store.addCertReqHistoryData(admin,cert1, userdata);
396         
397         userdata.setDN("C=SE,O=PrimeCA,OU=TestCertificateData,CN=CertReqHist2");
398         store.addCertReqHistoryData(admin,cert2, userdata);
399         log.debug("<test09addCertReqHist()");
400     }
401
402     /**
403      * checks that getCertReqHistory(Admin admin, BigInteger certificateSN, String issuerDN)
404      * returns the right data.
405      *
406      * @throws Exception error
407      */

408     public void test10getCertReqHistByIssuerDNAndSerial() throws Exception JavaDoc {
409         log.debug(">test10getCertReqHistByIssuerDNAndSerial()");
410         ICertificateStoreSessionRemote store = storehome.create();
411         
412         CertReqHistory certreqhist = store.getCertReqHistory(admin, cert1.getSerialNumber(),cert1.getIssuerDN().toString());
413         
414         assertNotNull("Error couldn't find the certificate request data stored previously", certreqhist);
415         
416         UserDataVO userdata = certreqhist.getUserDataVO();
417         assertTrue("Error wrong username.", (userdata.getUsername().equals(username)));
418         assertTrue("Error wrong DN.", (userdata.getDN().equals("C=SE,O=PrimeCA,OU=TestCertificateData,CN=CertReqHist1")));
419        
420         log.debug("<test10getCertReqHistByIssuerDNAndSerial()");
421     }
422     
423     /**
424      * checks that getCertReqHistory(Admin admin, String username)
425      * returns the the two CertReqHistory object previously stored.
426      *
427      * @throws Exception error
428      */

429     public void test11getCertReqHistByUsername() throws Exception JavaDoc {
430         log.debug(">test11getCertReqHistByUsername()");
431         ICertificateStoreSessionRemote store = storehome.create();
432         
433         Collection JavaDoc result = store.getCertReqHistory(admin, username);
434         assertTrue("Error size of the returned collection.", (result.size() == 2));
435
436         Iterator JavaDoc iter = result.iterator();
437         while(iter.hasNext()){
438           CertReqHistory certreqhist = (CertReqHistory) iter.next();
439           assertTrue("Error wrong DN", ((certreqhist.getUserDataVO().getDN().equals("C=SE,O=PrimeCA,OU=TestCertificateData,CN=CertReqHist1"))||
440                 (certreqhist.getUserDataVO().getDN().equals("C=SE,O=PrimeCA,OU=TestCertificateData,CN=CertReqHist2"))));
441         }
442         log.debug("<test11getCertReqHistByUsername()");
443     }
444     
445     /**
446      * Removes all the previously stored certreqhist data.
447      *
448      * @throws Exception error
449      */

450     public void test12removeCertReqHistData() throws Exception JavaDoc {
451         log.debug(">test12removeCertReqHistData()");
452         ICertificateStoreSessionRemote store = storehome.create();
453         
454         store.removeCertReqHistoryData(admin, CertTools.getFingerprintAsString(cert1));
455         store.removeCertReqHistoryData(admin, CertTools.getFingerprintAsString(cert2));
456         
457         CertReqHistory certreqhist = store.getCertReqHistory(admin, cert1.getSerialNumber(),cert1.getIssuerDN().toString());
458         assertNull("Error removing cert req history data, cert1 data is still there", certreqhist);
459         
460         certreqhist = store.getCertReqHistory(admin, cert2.getSerialNumber(),cert2.getIssuerDN().toString());
461         assertNull("Error removing cert req history data, cert2 data is still there", certreqhist);
462         
463         log.debug("<test12removeCertReqHistData()");
464     }
465     
466 }
467
Popular Tags