KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > se > anatom > ejbca > protocol > ProtocolOcspHttpTest


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.protocol;
15
16 import java.io.ByteArrayInputStream JavaDoc;
17 import java.io.ByteArrayOutputStream JavaDoc;
18 import java.io.IOException JavaDoc;
19 import java.io.InputStream JavaDoc;
20 import java.io.OutputStream JavaDoc;
21 import java.math.BigInteger JavaDoc;
22 import java.net.HttpURLConnection JavaDoc;
23 import java.net.URL JavaDoc;
24 import java.rmi.RemoteException JavaDoc;
25 import java.security.KeyPair JavaDoc;
26 import java.security.KeyPairGenerator JavaDoc;
27 import java.security.NoSuchProviderException JavaDoc;
28 import java.security.PublicKey JavaDoc;
29 import java.security.cert.X509Certificate JavaDoc;
30 import java.security.interfaces.RSAPrivateKey JavaDoc;
31 import java.util.ArrayList JavaDoc;
32 import java.util.Collection JavaDoc;
33 import java.util.Date JavaDoc;
34 import java.util.Hashtable JavaDoc;
35 import java.util.Iterator JavaDoc;
36
37 import javax.ejb.DuplicateKeyException JavaDoc;
38 import javax.naming.Context JavaDoc;
39 import javax.naming.NamingException JavaDoc;
40
41 import junit.framework.TestCase;
42 import junit.framework.TestSuite;
43
44 import org.apache.commons.lang.StringUtils;
45 import org.apache.log4j.Logger;
46 import org.bouncycastle.asn1.ASN1InputStream;
47 import org.bouncycastle.asn1.ASN1OctetString;
48 import org.bouncycastle.asn1.DEROctetString;
49 import org.bouncycastle.asn1.ocsp.OCSPObjectIdentifiers;
50 import org.bouncycastle.asn1.x509.X509Extension;
51 import org.bouncycastle.asn1.x509.X509Extensions;
52 import org.bouncycastle.jce.provider.JCEECPublicKey;
53 import org.bouncycastle.ocsp.BasicOCSPResp;
54 import org.bouncycastle.ocsp.CertificateID;
55 import org.bouncycastle.ocsp.OCSPException;
56 import org.bouncycastle.ocsp.OCSPReq;
57 import org.bouncycastle.ocsp.OCSPReqGenerator;
58 import org.bouncycastle.ocsp.OCSPResp;
59 import org.bouncycastle.ocsp.RevokedStatus;
60 import org.bouncycastle.ocsp.SingleResp;
61 import org.bouncycastle.ocsp.UnknownStatus;
62 import org.ejbca.core.ejb.authorization.IAuthorizationSessionHome;
63 import org.ejbca.core.ejb.authorization.IAuthorizationSessionRemote;
64 import org.ejbca.core.ejb.ca.caadmin.ICAAdminSessionHome;
65 import org.ejbca.core.ejb.ca.caadmin.ICAAdminSessionRemote;
66 import org.ejbca.core.ejb.ca.sign.ISignSessionHome;
67 import org.ejbca.core.ejb.ca.sign.ISignSessionRemote;
68 import org.ejbca.core.ejb.ca.store.CertificateDataPK;
69 import org.ejbca.core.ejb.ca.store.ICertificateStoreSessionHome;
70 import org.ejbca.core.ejb.ca.store.ICertificateStoreSessionRemote;
71 import org.ejbca.core.ejb.ra.IUserAdminSessionHome;
72 import org.ejbca.core.ejb.ra.IUserAdminSessionRemote;
73 import org.ejbca.core.model.SecConst;
74 import org.ejbca.core.model.ca.caadmin.CAExistsException;
75 import org.ejbca.core.model.ca.caadmin.CAInfo;
76 import org.ejbca.core.model.ca.caadmin.X509CAInfo;
77 import org.ejbca.core.model.ca.caadmin.extendedcaservices.ExtendedCAServiceInfo;
78 import org.ejbca.core.model.ca.caadmin.extendedcaservices.OCSPCAServiceInfo;
79 import org.ejbca.core.model.ca.catoken.CATokenConstants;
80 import org.ejbca.core.model.ca.catoken.CATokenInfo;
81 import org.ejbca.core.model.ca.catoken.SoftCATokenInfo;
82 import org.ejbca.core.model.ca.crl.RevokedCertInfo;
83 import org.ejbca.core.model.log.Admin;
84 import org.ejbca.core.model.ra.UserDataConstants;
85 import org.ejbca.util.Base64;
86 import org.ejbca.util.CertTools;
87 import org.ejbca.util.KeyTools;
88
89 import com.meterware.httpunit.GetMethodWebRequest;
90 import com.meterware.httpunit.HttpUnitOptions;
91 import com.meterware.httpunit.WebConversation;
92 import com.meterware.httpunit.WebRequest;
93 import com.meterware.httpunit.WebResponse;
94
95 /** Tests http pages of ocsp
96  **/

97 public class ProtocolOcspHttpTest extends TestCase {
98     private static Logger log = Logger.getLogger(ProtocolOcspHttpTest.class);
99
100     protected final String JavaDoc httpReqPath;
101     protected final String JavaDoc resourceOcsp;
102
103     protected static byte[] unknowncacertBytes = Base64.decode(("MIICLDCCAZWgAwIBAgIIbzEhUVZYO3gwDQYJKoZIhvcNAQEFBQAwLzEPMA0GA1UE" +
104             "AxMGVGVzdENBMQ8wDQYDVQQKEwZBbmFUb20xCzAJBgNVBAYTAlNFMB4XDTAyMDcw" +
105             "OTEyNDc1OFoXDTA0MDgxNTEyNTc1OFowLzEPMA0GA1UEAxMGVGVzdENBMQ8wDQYD" +
106             "VQQKEwZBbmFUb20xCzAJBgNVBAYTAlNFMIGdMA0GCSqGSIb3DQEBAQUAA4GLADCB" +
107             "hwKBgQDZlACHRwJnQKlgpMqlZQmxvCrJPpPFyhxvjDHlryhp/AQ6GCm+IkGUVlwL" +
108             "sCnjgZH5BXDNaVXpkmME8334HFsxVlXqmZ2GqyP6kptMjbWZ2SRLBRKjAcI7EJIN" +
109             "FPDIep9ZHXw1JDjFGoJ4TLFd99w9rQ3cB6zixORoyCZMw+iebwIBEaNTMFEwDwYD" +
110             "VR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUY3v0dqhUJI6ldKV3RKb0Xg9XklEwHwYD" +
111             "VR0jBBgwFoAUY3v0dqhUJI6ldKV3RKb0Xg9XklEwDQYJKoZIhvcNAQEFBQADgYEA" +
112             "i1P53jnSPLkyqm7i3nLNi+hG7rMgF+kRi6ZLKhzIPyKcAWV8iZCI8xl/GurbZ8zd" +
113             "nTiIOfQIP9eD/nhIIo7n4JOaTUeqgyafPsEgKdTiZfSdXjvy6rj5GiZ3DaGZ9SNK" +
114             "FgrCpX5kBKVbbQLO6TjJKCjX29CfoJ2TbP1QQ6UbBAY=").getBytes());
115
116     private static Context JavaDoc ctx;
117     private static ISignSessionHome home;
118     private static ISignSessionRemote remote;
119     protected ICertificateStoreSessionHome storehome;
120     private static IUserAdminSessionRemote usersession;
121     protected static int caid = 0;
122     protected static Admin admin;
123     protected static X509Certificate JavaDoc cacert = null;
124     private static X509Certificate JavaDoc ocspTestCert = null;
125     private static X509Certificate JavaDoc unknowncacert = null;
126
127     public static void main(String JavaDoc args[]) {
128         junit.textui.TestRunner.run(suite());
129     }
130
131
132     public static TestSuite suite() {
133         return new TestSuite(ProtocolOcspHttpTest.class);
134     }
135
136
137     public ProtocolOcspHttpTest(String JavaDoc name) throws Exception JavaDoc {
138         this(name,"http://127.0.0.1:8080/ejbca", "publicweb/status/ocsp");
139     }
140
141     protected ProtocolOcspHttpTest(String JavaDoc name, String JavaDoc reqP, String JavaDoc res) throws Exception JavaDoc {
142         super(name);
143         httpReqPath = reqP;
144         resourceOcsp = res;
145         // We want to get error responses without exceptions
146
HttpUnitOptions.setExceptionsThrownOnErrorStatus(false);
147
148         // Install BouncyCastle provider
149
CertTools.installBCProvider();
150
151         admin = new Admin(Admin.TYPE_BATCHCOMMANDLINE_USER);
152
153         ctx = getInitialContext();
154         Object JavaDoc obj = ctx.lookup("CAAdminSession");
155         ICAAdminSessionHome cahome = (ICAAdminSessionHome) javax.rmi.PortableRemoteObject.narrow(obj, ICAAdminSessionHome.class);
156         ICAAdminSessionRemote casession = cahome.create();
157         setCAID(casession);
158         CAInfo cainfo = casession.getCAInfo(admin, caid);
159         Collection JavaDoc certs = cainfo.getCertificateChain();
160         if (certs.size() > 0) {
161             Iterator JavaDoc certiter = certs.iterator();
162             cacert = (X509Certificate JavaDoc) certiter.next();
163         } else {
164             log.error("NO CACERT for caid " + caid);
165         }
166         obj = ctx.lookup("RSASignSession");
167         home = (ISignSessionHome) javax.rmi.PortableRemoteObject.narrow(obj, ISignSessionHome.class);
168         remote = home.create();
169         Object JavaDoc obj2 = ctx.lookup("CertificateStoreSession");
170         storehome = (ICertificateStoreSessionHome) javax.rmi.PortableRemoteObject.narrow(obj2, ICertificateStoreSessionHome.class);
171         obj = ctx.lookup("UserAdminSession");
172         IUserAdminSessionHome userhome = (IUserAdminSessionHome) javax.rmi.PortableRemoteObject.narrow(obj, IUserAdminSessionHome.class);
173         usersession = userhome.create();
174
175         unknowncacert = CertTools.getCertfromByteArray(unknowncacertBytes);
176
177     }
178
179     protected void setCAID(ICAAdminSessionRemote casession) throws RemoteException JavaDoc {
180         Collection JavaDoc caids = casession.getAvailableCAs(admin);
181         Iterator JavaDoc iter = caids.iterator();
182         if (iter.hasNext()) {
183             caid = ((Integer JavaDoc) iter.next()).intValue();
184         } else {
185             assertTrue("No active CA! Must have at least one active CA to run tests!", false);
186         }
187     }
188     protected void setUp() throws Exception JavaDoc {
189         log.debug(">setUp()");
190
191         log.debug("<setUp()");
192     }
193
194     protected void tearDown() throws Exception JavaDoc {
195     }
196
197     private Context JavaDoc getInitialContext() throws NamingException JavaDoc {
198         log.debug(">getInitialContext");
199         Context JavaDoc ctx = new javax.naming.InitialContext JavaDoc();
200         log.debug("<getInitialContext");
201         return ctx;
202     }
203
204     /**
205      * Generates a RSA key pair.
206      *
207      * @return KeyPair the generated key pair
208      *
209      * @throws Exception if en error occurs...
210      */

211     private static KeyPair JavaDoc genKeys() throws Exception JavaDoc {
212         KeyPairGenerator JavaDoc keygen = KeyPairGenerator.getInstance("RSA", "BC");
213         keygen.initialize(512);
214         log.debug("Generating keys, please wait...");
215         KeyPair JavaDoc rsaKeys = keygen.generateKeyPair();
216         log.debug("Generated " + rsaKeys.getPrivate().getAlgorithm() + " keys with length" +
217                 ((RSAPrivateKey JavaDoc) rsaKeys.getPrivate()).getModulus().bitLength());
218         return rsaKeys;
219     } // genKeys
220

221     public void test01Access() throws Exception JavaDoc {
222
223         WebConversation wc = new WebConversation();
224
225         // Hit with GET gives a 405 with OCSP: BAD_METHOD
226
WebRequest request = new GetMethodWebRequest(httpReqPath + '/' + resourceOcsp);
227         WebResponse response = wc.getResponse(request);
228         assertEquals("Response code", 405, response.getResponseCode());
229     }
230
231
232     /** Tests ocsp message
233      * @throws Exception error
234      */

235     public void test02OcspGood() throws Exception JavaDoc {
236         log.debug(">test02OcspGood()");
237
238         // find a CA (TestCA?) create a user and generate his cert
239
// send OCSP req to server and get good response
240
// change status of cert to bad status
241
// send OCSP req and get bad status
242
// (send crap message and get good error)
243

244         // Make user that we know...
245
boolean userExists = false;
246         try {
247             usersession.addUser(admin,"ocsptest","foo123","C=SE,O=AnaTom,CN=OCSPTest",null,"ocsptest@anatom.se",false,SecConst.EMPTY_ENDENTITYPROFILE,SecConst.CERTPROFILE_FIXED_ENDUSER,SecConst.USER_ENDUSER,SecConst.TOKEN_SOFT_PEM,0,caid);
248             log.debug("created user: ocsptest, foo123, C=SE, O=AnaTom, CN=OCSPTest");
249         } catch (RemoteException JavaDoc re) {
250             userExists = true;
251         } catch (DuplicateKeyException JavaDoc dke) {
252             userExists = true;
253         }
254
255         if (userExists) {
256             log.debug("User ocsptest already exists.");
257             usersession.changeUser(admin, "ocsptest", "foo123", "C=SE,O=AnaTom,CN=OCSPTest",null,"ocsptest@anatom.se",false, SecConst.EMPTY_ENDENTITYPROFILE,SecConst.CERTPROFILE_FIXED_ENDUSER,SecConst.USER_ENDUSER,SecConst.TOKEN_SOFT_PEM,0,UserDataConstants.STATUS_NEW, caid);
258             //usersession.setUserStatus(admin,"ocsptest",UserDataConstants.STATUS_NEW);
259
log.debug("Reset status to NEW");
260         }
261         // Generate certificate for the new user
262
KeyPair JavaDoc keys = genKeys();
263
264         // user that we know exists...
265
ocspTestCert = (X509Certificate JavaDoc) remote.createCertificate(admin, "ocsptest", "foo123", keys.getPublic());
266         assertNotNull("Misslyckades skapa cert", ocspTestCert);
267
268         // And an OCSP request
269
OCSPReqGenerator gen = new OCSPReqGenerator();
270         gen.addRequest(new CertificateID(CertificateID.HASH_SHA1, cacert, ocspTestCert.getSerialNumber()));
271         Hashtable JavaDoc exts = new Hashtable JavaDoc();
272         X509Extension ext = new X509Extension(false, new DEROctetString("123456789".getBytes()));
273         exts.put(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, ext);
274         gen.setRequestExtensions(new X509Extensions(exts));
275         OCSPReq req = gen.generate();
276
277         // Send the request and receive a singleResponse
278
SingleResp singleResp = sendOCSPPost(req.getEncoded(), "123456789");
279         
280         CertificateID certId = singleResp.getCertID();
281         assertEquals("Serno in response does not match serno in request.", certId.getSerialNumber(), ocspTestCert.getSerialNumber());
282         Object JavaDoc status = singleResp.getCertStatus();
283         assertEquals("Status is not null (good)", status, null);
284         log.debug("<test02OcspGood()");
285     }
286
287     /** Tests ocsp message
288      * @throws Exception error
289      */

290     public void test03OcspRevoked() throws Exception JavaDoc {
291         log.debug(">test03OcspRevoked()");
292         // Now revoke the certificate and try again
293
CertificateDataPK pk = new CertificateDataPK();
294         pk.fingerprint = CertTools.getFingerprintAsString(ocspTestCert);
295         ICertificateStoreSessionRemote store = storehome.create();
296         store.revokeCertificate(admin, ocspTestCert,null,RevokedCertInfo.REVOKATION_REASON_KEYCOMPROMISE);
297         // And an OCSP request
298
OCSPReqGenerator gen = new OCSPReqGenerator();
299         gen.addRequest(new CertificateID(CertificateID.HASH_SHA1, cacert, ocspTestCert.getSerialNumber()));
300         OCSPReq req = gen.generate();
301
302         // Send the request and receive a singleResponse
303
SingleResp singleResp = sendOCSPPost(req.getEncoded(), null);
304
305         CertificateID certId = singleResp.getCertID();
306         assertEquals("Serno in response does not match serno in request.", certId.getSerialNumber(), ocspTestCert.getSerialNumber());
307         Object JavaDoc status = singleResp.getCertStatus();
308         assertTrue("Status is not RevokedStatus", status instanceof RevokedStatus);
309         RevokedStatus rev = (RevokedStatus) status;
310         assertTrue("Status does not have reason", rev.hasRevocationReason());
311         int reason = rev.getRevocationReason();
312         assertEquals("Wrong revocation reason", reason, RevokedCertInfo.REVOKATION_REASON_KEYCOMPROMISE);
313         log.debug("<test03OcspRevoked()");
314     }
315
316     /** Tests ocsp message
317      * @throws Exception error
318      */

319     public void test04OcspUnknown() throws Exception JavaDoc {
320         log.debug(">test04OcspUnknown()");
321         // An OCSP request for an unknown certificate (not exist in db)
322
OCSPReqGenerator gen = new OCSPReqGenerator();
323         gen.addRequest(new CertificateID(CertificateID.HASH_SHA1, cacert, new BigInteger JavaDoc("1")));
324         OCSPReq req = gen.generate();
325         
326         // Send the request and receive a singleResponse
327
SingleResp singleResp = sendOCSPPost(req.getEncoded(), null);
328
329         CertificateID certId = singleResp.getCertID();
330         assertEquals("Serno in response does not match serno in request.", certId.getSerialNumber(), new BigInteger JavaDoc("1"));
331         Object JavaDoc status = singleResp.getCertStatus();
332         assertTrue("Status is not Unknown", status instanceof UnknownStatus);
333
334         log.debug("<test04OcspUnknown()");
335     }
336
337     /** Tests ocsp message
338      * @throws Exception error
339      */

340     public void test05OcspUnknownCA() throws Exception JavaDoc {
341         log.debug(">test05OcspUnknownCA()");
342         // An OCSP request for a certificate from an unknwon CA
343
OCSPReqGenerator gen = new OCSPReqGenerator();
344         gen.addRequest(new CertificateID(CertificateID.HASH_SHA1, unknowncacert, new BigInteger JavaDoc("1")));
345         OCSPReq req = gen.generate();
346         
347         // Send the request and receive a singleResponse
348
SingleResp singleResp = sendOCSPPost(req.getEncoded(), null);
349
350         CertificateID certId = singleResp.getCertID();
351         assertEquals("Serno in response does not match serno in request.", certId.getSerialNumber(), new BigInteger JavaDoc("1"));
352         Object JavaDoc status = singleResp.getCertStatus();
353         assertTrue("Status is not Unknown", status instanceof UnknownStatus);
354
355         log.debug("<test05OcspUnknownCA()");
356     }
357     
358     public void test06OcspSendWrongContentType() throws Exception JavaDoc {
359         // An OCSP request for a certificate from an unknwon CA
360
OCSPReqGenerator gen = new OCSPReqGenerator();
361         gen.addRequest(new CertificateID(CertificateID.HASH_SHA1, unknowncacert, new BigInteger JavaDoc("1")));
362         OCSPReq req = gen.generate();
363         // POST the OCSP request
364
URL JavaDoc url = new URL JavaDoc(httpReqPath + '/' + resourceOcsp);
365         HttpURLConnection JavaDoc con = (HttpURLConnection JavaDoc)url.openConnection();
366         // we are going to do a POST
367
con.setDoOutput(true);
368         con.setRequestMethod("POST");
369         // POST it, but don't add content type
370
OutputStream JavaDoc os = con.getOutputStream();
371         os.write(req.getEncoded());
372         os.close();
373         assertEquals("Response code", 400, con.getResponseCode());
374         
375     }
376
377     /** Tests ocsp message
378      * @throws Exception error
379      */

380     public void test07OcspEcdsaGood() throws Exception JavaDoc {
381         log.debug(">test07OcspEcdsaGood()");
382
383         int ecdsacaid = "CN=OCSPECDSATEST".hashCode();
384         X509Certificate JavaDoc ecdsacacert = addECDSACA("CN=OCSPECDSATEST", "prime192v1");
385         reloadKeys();
386         
387         // Make user that we know...
388
boolean userExists = false;
389         try {
390             usersession.addUser(admin,"ocsptest","foo123","C=SE,O=AnaTom,CN=OCSPTest",null,"ocsptest@anatom.se",false,SecConst.EMPTY_ENDENTITYPROFILE,SecConst.CERTPROFILE_FIXED_ENDUSER,SecConst.USER_ENDUSER,SecConst.TOKEN_SOFT_PEM,0,ecdsacaid);
391             log.debug("created user: ocsptest, foo123, C=SE, O=AnaTom, CN=OCSPTest");
392         } catch (RemoteException JavaDoc re) {
393             userExists = true;
394         } catch (DuplicateKeyException JavaDoc dke) {
395             userExists = true;
396         }
397
398         if (userExists) {
399             log.debug("User ocsptest already exists.");
400             usersession.changeUser(admin, "ocsptest", "foo123", "C=SE,O=AnaTom,CN=OCSPTest",null,"ocsptest@anatom.se",false, SecConst.EMPTY_ENDENTITYPROFILE,SecConst.CERTPROFILE_FIXED_ENDUSER,SecConst.USER_ENDUSER,SecConst.TOKEN_SOFT_PEM,0,UserDataConstants.STATUS_NEW, ecdsacaid);
401             //usersession.setUserStatus(admin,"ocsptest",UserDataConstants.STATUS_NEW);
402
log.debug("Reset status to NEW");
403         }
404         // Generate certificate for the new user
405
KeyPair JavaDoc keys = KeyTools.genKeys("prime192v1", "ECDSA");
406
407         // user that we know exists...
408
X509Certificate JavaDoc selfcert = CertTools.genSelfCert("CN=selfsigned", 1, null, keys.getPrivate(), keys.getPublic(), CATokenConstants.SIGALG_SHA256_WITH_ECDSA, false);
409         ocspTestCert = (X509Certificate JavaDoc) remote.createCertificate(admin, "ocsptest", "foo123", selfcert);
410         assertNotNull("Misslyckades skapa cert", ocspTestCert);
411
412         // And an OCSP request
413
OCSPReqGenerator gen = new OCSPReqGenerator();
414         gen.addRequest(new CertificateID(CertificateID.HASH_SHA1, ecdsacacert, ocspTestCert.getSerialNumber()));
415         Hashtable JavaDoc exts = new Hashtable JavaDoc();
416         X509Extension ext = new X509Extension(false, new DEROctetString("123456789".getBytes()));
417         exts.put(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, ext);
418         gen.setRequestExtensions(new X509Extensions(exts));
419         OCSPReq req = gen.generate();
420
421         // Send the request and receive a singleResponse
422
SingleResp singleResp = sendOCSPPost(req.getEncoded(), "123456789");
423         
424         CertificateID certId = singleResp.getCertID();
425         assertEquals("Serno in response does not match serno in request.", certId.getSerialNumber(), ocspTestCert.getSerialNumber());
426         Object JavaDoc status = singleResp.getCertStatus();
427         assertEquals("Status is not null (good)", status, null);
428         
429         log.debug("<test07OcspEcdsaGood()");
430     }
431
432     /** Tests ocsp message
433      * @throws Exception error
434      */

435     public void test08OcspEcdsaImplicitlyCAGood() throws Exception JavaDoc {
436         log.debug(">test08OcspEcdsaImplicitlyCAGood()");
437
438         int ecdsacaid = "CN=OCSPECDSAIMPCATEST".hashCode();
439         X509Certificate JavaDoc ecdsacacert = addECDSACA("CN=OCSPECDSAIMPCATEST", "implicitlyCA");
440         reloadKeys();
441         
442         // Make user that we know...
443
boolean userExists = false;
444         try {
445             usersession.addUser(admin,"ocsptest","foo123","C=SE,O=AnaTom,CN=OCSPTest",null,"ocsptest@anatom.se",false,SecConst.EMPTY_ENDENTITYPROFILE,SecConst.CERTPROFILE_FIXED_ENDUSER,SecConst.USER_ENDUSER,SecConst.TOKEN_SOFT_PEM,0,ecdsacaid);
446             log.debug("created user: ocsptest, foo123, C=SE, O=AnaTom, CN=OCSPTest");
447         } catch (RemoteException JavaDoc re) {
448             userExists = true;
449         } catch (DuplicateKeyException JavaDoc dke) {
450             userExists = true;
451         }
452
453         if (userExists) {
454             log.debug("User ocsptest already exists.");
455             usersession.changeUser(admin, "ocsptest", "foo123", "C=SE,O=AnaTom,CN=OCSPTest",null,"ocsptest@anatom.se",false, SecConst.EMPTY_ENDENTITYPROFILE,SecConst.CERTPROFILE_FIXED_ENDUSER,SecConst.USER_ENDUSER,SecConst.TOKEN_SOFT_PEM,0,UserDataConstants.STATUS_NEW, ecdsacaid);
456             //usersession.setUserStatus(admin,"ocsptest",UserDataConstants.STATUS_NEW);
457
log.debug("Reset status to NEW");
458         }
459         // Generate certificate for the new user
460
KeyPair JavaDoc keys = KeyTools.genKeys("implicitlyCA", "ECDSA");
461
462         // user that we know exists...
463
X509Certificate JavaDoc selfcert = CertTools.genSelfCert("CN=selfsigned", 1, null, keys.getPrivate(), keys.getPublic(), CATokenConstants.SIGALG_SHA256_WITH_ECDSA, false);
464         ocspTestCert = (X509Certificate JavaDoc) remote.createCertificate(admin, "ocsptest", "foo123", selfcert);
465         assertNotNull("Misslyckades skapa cert", ocspTestCert);
466
467         // And an OCSP request
468
OCSPReqGenerator gen = new OCSPReqGenerator();
469         gen.addRequest(new CertificateID(CertificateID.HASH_SHA1, ecdsacacert, ocspTestCert.getSerialNumber()));
470         Hashtable JavaDoc exts = new Hashtable JavaDoc();
471         X509Extension ext = new X509Extension(false, new DEROctetString("123456789".getBytes()));
472         exts.put(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, ext);
473         gen.setRequestExtensions(new X509Extensions(exts));
474         OCSPReq req = gen.generate();
475
476         // Send the request and receive a singleResponse
477
SingleResp singleResp = sendOCSPPost(req.getEncoded(), "123456789");
478         
479         CertificateID certId = singleResp.getCertID();
480         assertEquals("Serno in response does not match serno in request.", certId.getSerialNumber(), ocspTestCert.getSerialNumber());
481         Object JavaDoc status = singleResp.getCertStatus();
482         assertEquals("Status is not null (good)", status, null);
483         
484         log.debug("<test08OcspEcdsaImplicitlyCAGood()");
485     }
486
487     /**
488      * removes ECDSA CA
489      *
490      * @throws Exception error
491      */

492     public void test08RemoveECDSACA() throws Exception JavaDoc {
493         log.debug(">test08RemoveECDSACA()");
494         Context JavaDoc context = getInitialContext();
495         Object JavaDoc obj1 = context.lookup("CAAdminSession");
496         ICAAdminSessionHome cacheHome = (ICAAdminSessionHome) javax.rmi.PortableRemoteObject.narrow(obj1, ICAAdminSessionHome.class);
497         ICAAdminSessionRemote cacheAdmin = cacheHome.create();
498         cacheAdmin.removeCA(admin, "CN=OCSPECDSATEST".hashCode());
499         cacheAdmin.removeCA(admin, "CN=OCSPECDSAIMPCATEST".hashCode());
500         log.debug("<test08RemoveECDSACA()");
501     }
502
503     //
504
// Private helper methods
505
//
506

507     /**
508      * adds a CA Using ECDSA keys to the database.
509      *
510      * It also checks that the CA is stored correctly.
511      *
512      * @throws Exception error
513      */

514     private X509Certificate JavaDoc addECDSACA(String JavaDoc dn, String JavaDoc keySpec) throws Exception JavaDoc {
515         log.debug(">addECDSACA()");
516         boolean ret = false;
517         X509Certificate JavaDoc cacert = null;
518         try {
519             Context JavaDoc context = getInitialContext();
520             IAuthorizationSessionHome authorizationsessionhome = (IAuthorizationSessionHome) javax.rmi.PortableRemoteObject.narrow(context.lookup("AuthorizationSession"), IAuthorizationSessionHome.class);
521             IAuthorizationSessionRemote authorizationsession = authorizationsessionhome.create();
522             authorizationsession.initialize(admin, dn.hashCode());
523             Object JavaDoc obj1 = context.lookup("CAAdminSession");
524             ICAAdminSessionHome cacheHome = (ICAAdminSessionHome) javax.rmi.PortableRemoteObject.narrow(obj1, ICAAdminSessionHome.class);
525             ICAAdminSessionRemote cacheAdmin = cacheHome.create();
526
527             SoftCATokenInfo catokeninfo = new SoftCATokenInfo();
528             catokeninfo.setSignKeySpec(keySpec);
529             catokeninfo.setEncKeySpec("1024");
530             catokeninfo.setSignKeyAlgorithm(SoftCATokenInfo.KEYALGORITHM_ECDSA);
531             catokeninfo.setEncKeyAlgorithm(SoftCATokenInfo.KEYALGORITHM_RSA);
532             catokeninfo.setSignatureAlgorithm(CATokenInfo.SIGALG_SHA256_WITH_ECDSA);
533             catokeninfo.setEncryptionAlgorithm(CATokenInfo.SIGALG_SHA1_WITH_RSA);
534             // Create and active OSCP CA Service.
535
ArrayList JavaDoc extendedcaservices = new ArrayList JavaDoc();
536             extendedcaservices.add(new OCSPCAServiceInfo(ExtendedCAServiceInfo.STATUS_ACTIVE,
537                     "CN=OCSPSignerCertificate, " + dn,
538                     "",
539                     keySpec,
540                     CATokenConstants.KEYALGORITHM_ECDSA));
541
542
543             X509CAInfo cainfo = new X509CAInfo(dn,
544                     dn, SecConst.CA_ACTIVE, new Date JavaDoc(),
545                     "", SecConst.CERTPROFILE_FIXED_ROOTCA,
546                     365,
547                     null, // Expiretime
548
CAInfo.CATYPE_X509,
549                     CAInfo.SELFSIGNED,
550                     (Collection JavaDoc) null,
551                     catokeninfo,
552                     "JUnit ECDSA CA",
553                     -1, null,
554                     "2.5.29.32.0", // PolicyId
555
24, // CRLPeriod
556
0, // CRLIssueInterval
557
10, // CRLOverlapTime
558
new ArrayList JavaDoc(),
559                     true, // Authority Key Identifier
560
false, // Authority Key Identifier Critical
561
true, // CRL Number
562
false, // CRL Number Critical
563
null, // defaultcrldistpoint
564
null, // defaultcrlissuer
565
null, // defaultocsplocator
566
true, // Finish User
567
extendedcaservices,
568                     false, // use default utf8 settings
569
new ArrayList JavaDoc(), // Approvals Settings
570
1, // Number of Req approvals
571
false); // Use UTF8 subject DN by default
572

573
574             cacheAdmin.createCA(admin, cainfo);
575
576
577             CAInfo info = cacheAdmin.getCAInfo(admin, dn);
578
579             X509Certificate JavaDoc cert = (X509Certificate JavaDoc) info.getCertificateChain().iterator().next();
580             assertTrue("Error in created ca certificate", cert.getSubjectDN().toString().equals(dn));
581             assertTrue("Creating CA failed", info.getSubjectDN().equals(dn));
582             PublicKey JavaDoc pk = cert.getPublicKey();
583             if (pk instanceof JCEECPublicKey) {
584                 JCEECPublicKey ecpk = (JCEECPublicKey) pk;
585                 assertEquals(ecpk.getAlgorithm(), "EC");
586                 org.bouncycastle.jce.spec.ECParameterSpec spec = ecpk.getParameters();
587                 if (StringUtils.equals(keySpec, "implicitlyCA")) {
588                     assertNull("ImplicitlyCA must have null spec", spec);
589                 } else {
590                     assertNotNull("prime192v1 must not have null spec", spec);
591                 }
592             } else {
593                 assertTrue("Public key is not EC", false);
594             }
595
596             ret = true;
597             Collection JavaDoc coll = info.getCertificateChain();
598             Object JavaDoc[] certs = coll.toArray();
599             cacert = (X509Certificate JavaDoc)certs[0];
600         } catch (CAExistsException pee) {
601             log.info("CA exists.");
602         }
603
604         assertTrue("Creating ECDSA CA failed", ret);
605         log.debug("<addECDSACA()");
606         return cacert;
607     }
608
609
610     protected SingleResp sendOCSPPost(byte[] ocspPackage, String JavaDoc nonce) throws IOException JavaDoc, OCSPException, NoSuchProviderException JavaDoc {
611         // POST the OCSP request
612
URL JavaDoc url = new URL JavaDoc(httpReqPath + '/' + resourceOcsp);
613         HttpURLConnection JavaDoc con = (HttpURLConnection JavaDoc)url.openConnection();
614         // we are going to do a POST
615
con.setDoOutput(true);
616         con.setRequestMethod("POST");
617
618         // POST it
619
con.setRequestProperty("Content-Type", "application/ocsp-request");
620         OutputStream JavaDoc os = con.getOutputStream();
621         os.write(ocspPackage);
622         os.close();
623         assertEquals("Response code", 200, con.getResponseCode());
624         assertEquals("Content-Type", "application/ocsp-response", con.getContentType());
625         ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
626         // This works for small requests, and OCSP requests are small
627
InputStream JavaDoc in = con.getInputStream();
628         int b = in.read();
629         while (b != -1) {
630             baos.write(b);
631             b = in.read();
632         }
633         baos.flush();
634         in.close();
635         byte[] respBytes = baos.toByteArray();
636         OCSPResp response = new OCSPResp(new ByteArrayInputStream JavaDoc(respBytes));
637         assertEquals("Response status not zero.", response.getStatus(), 0);
638         BasicOCSPResp brep = (BasicOCSPResp) response.getResponseObject();
639         X509Certificate JavaDoc[] chain = brep.getCerts("BC");
640         boolean verify = brep.verify(chain[0].getPublicKey(), "BC");
641         assertTrue("Response failed to verify.", verify);
642         // Check nonce (if we sent one)
643
if (nonce != null) {
644             byte[] noncerep = brep.getExtensionValue(OCSPObjectIdentifiers.id_pkix_ocsp_nonce.getId());
645             assertNotNull(noncerep);
646             ASN1InputStream ain = new ASN1InputStream(noncerep);
647             ASN1OctetString oct = ASN1OctetString.getInstance(ain.readObject());
648             assertEquals(nonce, new String JavaDoc(oct.getOctets()));
649         }
650         SingleResp[] singleResps = brep.getResponses();
651         assertEquals("No of SingResps should be 1.", singleResps.length, 1);
652         SingleResp singleResp = singleResps[0];
653         return singleResp;
654     }
655     
656     protected void reloadKeys() throws IOException JavaDoc, OCSPException, NoSuchProviderException JavaDoc {
657         // POST the OCSP request
658
URL JavaDoc url = new URL JavaDoc(httpReqPath + '/' + resourceOcsp+"?reloadkeys=true");
659         HttpURLConnection JavaDoc con = (HttpURLConnection JavaDoc)url.openConnection();
660         // we are going to do a POST
661
con.setDoOutput(true);
662         con.setRequestMethod("GET");
663
664         // POST it
665
con.setRequestProperty("reloadkeys", "true");
666         con.connect();
667         assertEquals("Response code", 405, con.getResponseCode());
668         con.disconnect();
669     }
670 }
671
Popular Tags