KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > se > anatom > ejbca > ca > sign > TestSignSession


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.sign;
15
16 import java.io.ByteArrayOutputStream JavaDoc;
17 import java.rmi.RemoteException JavaDoc;
18 import java.security.KeyPair JavaDoc;
19 import java.security.PublicKey JavaDoc;
20 import java.security.cert.X509Certificate JavaDoc;
21 import java.security.interfaces.RSAPublicKey JavaDoc;
22 import java.util.ArrayList JavaDoc;
23 import java.util.Arrays JavaDoc;
24 import java.util.Calendar JavaDoc;
25 import java.util.Collection JavaDoc;
26 import java.util.Date JavaDoc;
27
28 import javax.ejb.DuplicateKeyException JavaDoc;
29 import javax.naming.Context JavaDoc;
30 import javax.naming.NamingException JavaDoc;
31
32 import junit.framework.TestCase;
33
34 import org.apache.log4j.Logger;
35 import org.bouncycastle.asn1.DEROutputStream;
36 import org.bouncycastle.asn1.x509.qualified.ETSIQCObjectIdentifiers;
37 import org.bouncycastle.asn1.x509.qualified.RFC3739QCObjectIdentifiers;
38 import org.bouncycastle.jce.PKCS10CertificationRequest;
39 import org.bouncycastle.jce.provider.JCEECPublicKey;
40 import org.ejbca.core.ejb.ca.caadmin.ICAAdminSessionHome;
41 import org.ejbca.core.ejb.ca.caadmin.ICAAdminSessionRemote;
42 import org.ejbca.core.ejb.ca.sign.ISignSessionHome;
43 import org.ejbca.core.ejb.ca.sign.ISignSessionRemote;
44 import org.ejbca.core.ejb.ca.store.ICertificateStoreSessionHome;
45 import org.ejbca.core.ejb.ca.store.ICertificateStoreSessionRemote;
46 import org.ejbca.core.ejb.ra.IUserAdminSessionHome;
47 import org.ejbca.core.ejb.ra.IUserAdminSessionRemote;
48 import org.ejbca.core.ejb.ra.raadmin.IRaAdminSessionHome;
49 import org.ejbca.core.ejb.ra.raadmin.IRaAdminSessionRemote;
50 import org.ejbca.core.model.SecConst;
51 import org.ejbca.core.model.ca.IllegalKeyException;
52 import org.ejbca.core.model.ca.caadmin.CAInfo;
53 import org.ejbca.core.model.ca.catoken.CATokenConstants;
54 import org.ejbca.core.model.ca.certificateprofiles.CertificateProfile;
55 import org.ejbca.core.model.ca.certificateprofiles.EndUserCertificateProfile;
56 import org.ejbca.core.model.log.Admin;
57 import org.ejbca.core.model.ra.UserDataConstants;
58 import org.ejbca.core.model.ra.raadmin.EndEntityProfile;
59 import org.ejbca.core.protocol.IResponseMessage;
60 import org.ejbca.core.protocol.PKCS10RequestMessage;
61 import org.ejbca.util.Base64;
62 import org.ejbca.util.CertTools;
63 import org.ejbca.util.KeyTools;
64 import org.ejbca.util.cert.QCStatementExtension;
65 import org.ejbca.util.dn.DnComponents;
66
67
68 /**
69  * Tests signing session.
70  *
71  * @version $Id: TestSignSession.java,v 1.25.2.3 2007/06/05 13:37:23 anatom Exp $
72  */

73 public class TestSignSession extends TestCase {
74     static byte[] keytoolp10 = Base64.decode(("MIIBbDCB1gIBADAtMQ0wCwYDVQQDEwRUZXN0MQ8wDQYDVQQKEwZBbmFUb20xCzAJBgNVBAYTAlNF" +
75             "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDY+ATE4ZB0oKfmXStu8J+do0GhTag6rOGtoydI" +
76             "eNX9DdytlsmXDyONKl8746478/3HXdx9rA0RevUizKSataMpDsb3TjprRjzBTvYPZSIfzko6s8g6" +
77             "AZLO07xCFOoDmyRzb9k/KEZsMls0ujx79CQ9p5K4rg2ksjmDeW7DaPMphQIDAQABoAAwDQYJKoZI" +
78             "hvcNAQEFBQADgYEAyJVobqn6wGRoEsdHxjoqPXw8fLrQyBGEwXccnVpI4kv9iIZ45Xres0LrOwtS" +
79             "kFLbpn0guEzhxPBbL6mhhmDDE4hbbHJp1Kh6gZ4Bmbb5FrwpvUyrSjTIwwRC7GAT00A1kOjl9jCC" +
80             "XCfJkJH2QleCy7eKANq+DDTXzpEOvL/UqN0=").getBytes());
81     static byte[] oldbcp10 = Base64.decode(("MIIBbDCB1gIBADAtMQswCQYDVQQGEwJTRTEPMA0GA1UEChMGQW5hVG9tMQ0wCwYDVQQDEwRUZXN0" +
82             "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCzN9nDdwmq23/RLGisvR3CRO9JSem2QZ7JC7nr" +
83             "NlbxQBLVqlkypT/lxMMur+lTX1S+jBaqXjtirhZTVaV5C/+HObWZ5vrj30lmsCdgzFybSzVxBz0l" +
84             "XC0UEDbgBml/hO70cSDdmyw3YE9g5eH3wdYs2FCTzexRF3kNAVHNUa8svwIDAQABoAAwDQYJKoZI" +
85             "hvcNAQEFBQADgYEAm6uRSyEmyCcs652Ttg2npm6JZPFT2qwSl4dviyIKJbn6j+meCzvn2TMP10d8" +
86             "7Ak5sv5NJew1XGkM4mGpF9cfcVshxLVlW+cgq0749fWbyS8KlgQP/ANh3DkLl8k5E+3Wnbi0JjCV" +
87             "Xe1s44+K2solX8jOtryoR4TMJ6p9HpsuO68=").getBytes());
88     static byte[] iep10 = Base64.decode(("MIICnTCCAgYCAQAwGzEZMBcGA1UEAxMQNkFFSzM0N2Z3OHZXRTQyNDCBnzANBgkq" +
89             "hkiG9w0BAQEFAAOBjQAwgYkCgYEAukW70HN9bt5x2AiSZm7y8GXQuyp1jN2OIvqU" +
90             "sr0dzLIOFt1H8GPJkL80wx3tLDj3xJfWJdww3TqExsxMSP+qScoYKIOeNBb/2OMW" +
91             "p/k3DThCOewPebmt+M08AClq5WofXTG+YxyJgXWbMTNfXKIUyR0Ju4Spmg6Y4eJm" +
92             "GXTG7ZUCAwEAAaCCAUAwGgYKKwYBBAGCNw0CAzEMFgo1LjAuMjE5NS4yMCAGCisG" +
93             "AQQBgjcCAQ4xEjAQMA4GA1UdDwEB/wQEAwIE8DCB/wYKKwYBBAGCNw0CAjGB8DCB" +
94             "7QIBAR5cAE0AaQBjAHIAbwBzAG8AZgB0ACAARQBuAGgAYQBuAGMAZQBkACAAQwBy" +
95             "AHkAcAB0AG8AZwByAGEAcABoAGkAYwAgAFAAcgBvAHYAaQBkAGUAcgAgAHYAMQAu" +
96             "ADADgYkAjuYPzZPpbLgCWYnXoNeX2gS6nuI4osrWHlQQKcS67VJclhELlnT3hBb9" +
97             "Blr7I0BsJ/lguZvZFTZnC1bMeNULRg17bhExTg+nUovzPcJhMvG7G3DR17PrJ7V+" +
98             "egHAsQV4dQC2hOGGhOnv88JhP9Pwpso3t2tqJROa5ZNRRSJSkw8AAAAAAAAAADAN" +
99             "BgkqhkiG9w0BAQQFAAOBgQCL5k4bJt265j63qB/9GoQb1XFOPSar1BDFi+veCPA2" +
100             "GJ/vRXt77Vcr4inx9M51iy87FNcGGsmyesBoDg73p06UxpIDhkL/WpPwZAfQhWGe" +
101             "o/gWydmP/hl3uEfE0E4WG02UXtNwn3ziIiJM2pBCGQQIN2rFggyD+aTxwAwOU7Z2" + "fw==").getBytes());
102     static byte[] openscep = Base64.decode(("MIIFSwYJKoZIhvcNAQcCoIIFPDCCBTgCAQExDjAMBggqhkiG9w0CBQUAMIICMwYJ" +
103             "KoZIhvcNAQcBoIICJASCAiAwggIcBgkqhkiG9w0BBwOgggINMIICCQIBADGB1TCB" +
104             "0gIBADA7MC8xDzANBgNVBAMTBlRlc3RDQTEPMA0GA1UEChMGQW5hVG9tMQswCQYD" +
105             "VQQGEwJTRQIIbzEhUVZYO3gwDQYJKoZIhvcNAQEBBQAEgYDJP3tsx1KMC+Ws3gcV" +
106             "gpvatMgxocUrKS2Z5BRj7z8HE/BySwa40fwzpBXq3xhakclrdK9D6Bb7I2oTqaNo" +
107             "y25tk2ykow8px1HEerGg5eCIDeAwX4IGurKn+ajls4vWntybgtosAFPLuBO2sdfy" +
108             "VhTv+iFxkl+lZgcRfpJhmqfOJjCCASoGCSqGSIb3DQEHATARBgUrDgMCBwQIapUt" +
109             "FKgA/KmAggEIpzjb5ONkiT7gPs5VeQ6a2e3IdXMgZTRknqZZRRzRovKwp17LJPkA" +
110             "AF9vQKCk6IQwM1dY4NAhu/mCvkfQwwVgML+rbsx7cYH5VuMxw6xw79CnGZbcgOoE" +
111             "lhfYR9ytfZFAVjs8TF/cx1GfuxxN/3RdXzwIFmvPRX1SPh83ueMbGTHjmk0/kweE" +
112             "9XcLkI85jTyG/Dsq3mUlWDS4qQg4sSbFAvkHgmCl0DQd2qW3eV9rCDbfPNjc+2dq" +
113             "nG5EwjX1UVYS2TSWy7vu6MQvKtEWFP4B10+vGBcVE8fZ4IxL9TDQ4UMz3gfFIQSc" +
114             "Moq4lw7YKmywbbyieGGYJuXDX/0gUBKj/MrP9s3L12bLoIIBajCCAWYwggEQoAMC" +
115             "AQMCIDNGREQzNUM5NzZDODlENjcwRjNCM0IxOTgxQjhDMzA2MA0GCSqGSIb3DQEB" +
116             "BAUAMCwxCzAJBgNVBAYTAlNFMQ8wDQYDVQQKEwZBbmFUb20xDDAKBgNVBAMTA2Zv" +
117             "bzAeFw0wMzA2MTkwODQ3NDlaFw0wMzA3MTkwODQ3NDlaMCwxCzAJBgNVBAYTAlNF" +
118             "MQ8wDQYDVQQKEwZBbmFUb20xDDAKBgNVBAMTA2ZvbzBcMA0GCSqGSIb3DQEBAQUA" +
119             "A0sAMEgCQQDLfHDEOse6Mbi02egr2buI9mgWC0ur9dvGmLiIxmNg1TNhn1WHj5Zy" +
120             "VsjKyLoVuVqgGRPYVA73ItANF8RNBAt9AgMBAAEwDQYJKoZIhvcNAQEEBQADQQCw" +
121             "9kQsl3M0Ag1892Bu3izeZOYKpze64kJ7iGuYmN8atkdO8Rpp4Jn0W6vvUYQcat2a" +
122             "Jzf6h3xfEQ7m8CzvaQ2/MYIBfDCCAXgCAQEwUDAsMQswCQYDVQQGEwJTRTEPMA0G" +
123             "A1UEChMGQW5hVG9tMQwwCgYDVQQDEwNmb28CIDNGREQzNUM5NzZDODlENjcwRjNC" +
124             "M0IxOTgxQjhDMzA2MAwGCCqGSIb3DQIFBQCggcEwEgYKYIZIAYb4RQEJAjEEEwIx" +
125             "OTAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEPFw0wMzA2" +
126             "MTkwODQ3NDlaMB8GCSqGSIb3DQEJBDESBBCevtHE4n3my5B7Q+MiKj04MCAGCmCG" +
127             "SAGG+EUBCQUxEgQQwH1TAMlSzz1d3SNXoOARkTAwBgpghkgBhvhFAQkHMSITIDNG" +
128             "REQzNUM5NzZDODlENjcwRjNCM0IxOTgxQjhDMzA2MA0GCSqGSIb3DQEBAQUABEAW" +
129             "r+9YB3t1750Aj4bm5JAHv80VhzkrPmVLZqsJdC2DGn3UQFp1FhXo4od2xGpeg+pZ" +
130             "b0B6kUt+uxvuq3PbagLi").getBytes());
131     static byte[] keytooldsa = Base64.decode(("MIICNjCCAfQCAQAwMTERMA8GA1UEAxMIRFNBIFRlc3QxDzANBgNVBAoTBkFuYXRvbTELMAkGA1UE" +
132             "BhMCU0UwggG4MIIBLAYHKoZIzjgEATCCAR8CgYEA/X9TgR11EilS30qcLuzk5/YRt1I870QAwx4/" +
133             "gLZRJmlFXUAiUftZPY1Y+r/F9bow9subVWzXgTuAHTRv8mZgt2uZUKWkn5/oBHsQIsJPu6nX/rfG" +
134             "G/g7V+fGqKYVDwT7g/bTxR7DAjVUE1oWkTL2dfOuK2HXKu/yIgMZndFIAccCFQCXYFCPFSMLzLKS" +
135             "uYKi64QL8Fgc9QKBgQD34aCF1ps93su8q1w2uFe5eZSvu/o66oL5V0wLPQeCZ1FZV4661FlP5nEH" +
136             "EIGAtEkWcSPoTCgWE7fPCTKMyKbhPBZ6i1R8jSjgo64eK7OmdZFuo38L+iE1YvH7YnoBJDvMpPG+" +
137             "qFGQiaiD3+Fa5Z8GkotmXoB7VSVkAUw7/s9JKgOBhQACgYEAiVCUaC95mHaU3C9odWcuJ8j3fT6z" +
138             "bSR02CVFC0F6QO5s2Tx3JYWrm5aAjWkXWJfeYOR6qBSwX0R1US3rDI0Kepsrdco2q7wGSo+235KL" +
139             "Yfl7tQ9RLOKUGX/1c5+XuvN1ZbGy0yUw3Le16UViahWmmx6FM1sW6M48U7C/CZOyoxagADALBgcq" +
140             "hkjOOAQDBQADLwAwLAIUQ+S2iFA1y7dfDWUCg7j1Nc8RW0oCFFhnDlU69xFRMeXXn1C/Oi+8pwrQ").getBytes());
141     private static Logger log = Logger.getLogger(TestSignSession.class);
142     private static Context JavaDoc ctx;
143     private static ISignSessionHome home;
144     private static ISignSessionRemote remote;
145     private static IUserAdminSessionRemote usersession;
146     private static IRaAdminSessionRemote rasession;
147     private static ICertificateStoreSessionRemote storesession;
148     private static KeyPair JavaDoc rsakeys=null;
149     private static KeyPair JavaDoc ecdsakeys=null;
150     private static KeyPair JavaDoc ecdsaimplicitlyca=null;
151     private static int rsacaid = 0;
152     private static int ecdsacaid = 0;
153     private static int ecdsaimplicitlycacaid = 0;
154     private static int rsamgf1cacaid = 0;
155     X509Certificate JavaDoc rsacacert = null;
156     X509Certificate JavaDoc ecdsacacert = null;
157     X509Certificate JavaDoc ecdsaimplicitlycacacert = null;
158     X509Certificate JavaDoc rsamgf1cacacert = null;
159     private Admin admin;
160
161     /**
162      * Creates a new TestSignSession object.
163      *
164      * @param name name
165      */

166     public TestSignSession(String JavaDoc name) throws Exception JavaDoc {
167         super(name);
168
169         // Install BouncyCastle provider
170
CertTools.installBCProvider();
171         if (rsakeys == null) {
172             rsakeys = KeyTools.genKeys("1024", CATokenConstants.KEYALGORITHM_RSA);
173         }
174         if (ecdsakeys == null) {
175             ecdsakeys = KeyTools.genKeys("prime192v1", CATokenConstants.KEYALGORITHM_ECDSA);
176         }
177         if (ecdsaimplicitlyca == null) {
178             ecdsaimplicitlyca = KeyTools.genKeys("implicitlyCA", CATokenConstants.KEYALGORITHM_ECDSA);
179         }
180
181         admin = new Admin(Admin.TYPE_BATCHCOMMANDLINE_USER);
182
183         ctx = getInitialContext();
184         Object JavaDoc obj = ctx.lookup("CAAdminSession");
185         ICAAdminSessionHome cahome = (ICAAdminSessionHome) javax.rmi.PortableRemoteObject.narrow(obj, ICAAdminSessionHome.class);
186         ICAAdminSessionRemote casession = cahome.create();
187         CAInfo inforsa = casession.getCAInfo(admin, "TEST");
188         rsacaid = inforsa.getCAId();
189         if (rsacaid == 0){
190             assertTrue("No active RSA CA! Must have at least one active CA to run tests!", false);
191         }
192         CAInfo infoecdsa = casession.getCAInfo(admin, "TESTECDSA");
193         ecdsacaid = infoecdsa.getCAId();
194         if (ecdsacaid == 0){
195             assertTrue("No active ECDSA CA! Must have at least one active CA to run tests!", false);
196         }
197         CAInfo infoecdsaimplicitlyca = casession.getCAInfo(admin, "TESTECDSAImplicitlyCA");
198         ecdsaimplicitlycacaid = infoecdsaimplicitlyca.getCAId();
199         if (ecdsaimplicitlycacaid == 0){
200             assertTrue("No active ECDSA ImplicitlyCA CA! Must have at least one active CA to run tests!", false);
201         }
202         CAInfo inforsamgf1ca = casession.getCAInfo(admin, "TESTSha256WithMGF1");
203         rsamgf1cacaid = inforsamgf1ca.getCAId();
204         if (rsamgf1cacaid == 0){
205             assertTrue("No active RSA MGF1 CA! Must have at least one active CA to run tests!", false);
206         }
207         Collection JavaDoc coll = inforsa.getCertificateChain();
208         Object JavaDoc[] objs = coll.toArray();
209         rsacacert = (X509Certificate JavaDoc)objs[0];
210         coll = infoecdsa.getCertificateChain();
211         objs = coll.toArray();
212         ecdsacacert = (X509Certificate JavaDoc)objs[0];
213         coll = infoecdsaimplicitlyca.getCertificateChain();
214         objs = coll.toArray();
215         ecdsaimplicitlycacacert = (X509Certificate JavaDoc)objs[0];
216         coll = inforsamgf1ca.getCertificateChain();
217         objs = coll.toArray();
218         rsamgf1cacacert = (X509Certificate JavaDoc)objs[0];
219         
220         obj = ctx.lookup("RSASignSession");
221         home = (ISignSessionHome) javax.rmi.PortableRemoteObject.narrow(obj, ISignSessionHome.class);
222         remote = home.create();
223
224         obj = ctx.lookup("UserAdminSession");
225         IUserAdminSessionHome userhome = (IUserAdminSessionHome) javax.rmi.PortableRemoteObject.narrow(obj, IUserAdminSessionHome.class);
226         usersession = userhome.create();
227         
228         obj = ctx.lookup("RaAdminSession");
229         IRaAdminSessionHome rahome = (IRaAdminSessionHome) javax.rmi.PortableRemoteObject.narrow(obj, IRaAdminSessionHome.class);
230         rasession = rahome.create();
231
232         obj = ctx.lookup("CertificateStoreSession");
233         ICertificateStoreSessionHome storehome = (ICertificateStoreSessionHome) javax.rmi.PortableRemoteObject.narrow(obj, ICertificateStoreSessionHome.class);
234         storesession = storehome.create();
235
236     }
237
238     protected void setUp() throws Exception JavaDoc {
239         log.debug(">setUp()");
240
241         log.debug("<setUp()");
242     }
243
244     protected void tearDown() throws Exception JavaDoc {
245     }
246
247     private Context JavaDoc getInitialContext() throws NamingException JavaDoc {
248         log.debug(">getInitialContext");
249
250         Context JavaDoc ctx = new javax.naming.InitialContext JavaDoc();
251         log.debug("<getInitialContext");
252
253         return ctx;
254     }
255
256
257     /**
258      * creates new user
259      *
260      * @throws Exception if en error occurs...
261      */

262     public void test01CreateNewUser() throws Exception JavaDoc {
263         log.debug(">test01CreateNewUser()");
264
265         // Make user that we know...
266
boolean userExists = false;
267         try {
268             usersession.addUser(admin,"foo","foo123","C=SE,O=AnaTom,CN=foo",null,"foo@anatom.se",false,SecConst.EMPTY_ENDENTITYPROFILE,SecConst.CERTPROFILE_FIXED_ENDUSER,SecConst.USER_ENDUSER,SecConst.TOKEN_SOFT_PEM,0,rsacaid);
269             log.debug("created user: foo, foo123, C=SE, O=AnaTom, CN=foo");
270         } catch (RemoteException JavaDoc re) {
271             userExists = true;
272         } catch (DuplicateKeyException JavaDoc dke) {
273             userExists = true;
274         }
275         if (userExists) {
276             log.info("User foo already exists, resetting status.");
277             usersession.changeUser(admin,"foo","foo123","C=SE,O=AnaTom,CN=foo",null,"foo@anatom.se",false,SecConst.EMPTY_ENDENTITYPROFILE,SecConst.CERTPROFILE_FIXED_ENDUSER,SecConst.USER_ENDUSER,SecConst.TOKEN_SOFT_PEM,0,UserDataConstants.STATUS_NEW,rsacaid);
278             //usersession.setUserStatus(admin,"foo",UserDataConstants.STATUS_NEW);
279
log.debug("Reset status to NEW");
280         }
281         userExists = false;
282         try {
283             usersession.addUser(admin,"fooecdsa","foo123","C=SE,O=AnaTom,CN=fooecdsa",null,"foo@anatom.se",false,SecConst.EMPTY_ENDENTITYPROFILE,SecConst.CERTPROFILE_FIXED_ENDUSER,SecConst.USER_ENDUSER,SecConst.TOKEN_SOFT_PEM,0,ecdsacaid);
284             log.debug("created user: fooecdsa, foo123, C=SE, O=AnaTom, CN=fooecdsa");
285         } catch (RemoteException JavaDoc re) {
286             userExists = true;
287         } catch (DuplicateKeyException JavaDoc dke) {
288             userExists = true;
289         }
290         if (userExists) {
291             log.info("User fooecdsa already exists, resetting status.");
292             usersession.setUserStatus(admin,"fooecdsa",UserDataConstants.STATUS_NEW);
293             log.debug("Reset status to NEW");
294         }
295         userExists = false;
296         try {
297             usersession.addUser(admin,"fooecdsaimpca","foo123","C=SE,O=AnaTom,CN=fooecdsaimpca",null,"foo@anatom.se",false,SecConst.EMPTY_ENDENTITYPROFILE,SecConst.CERTPROFILE_FIXED_ENDUSER,SecConst.USER_ENDUSER,SecConst.TOKEN_SOFT_PEM,0,ecdsaimplicitlycacaid);
298             log.debug("created user: fooecdsaimpca, foo123, C=SE, O=AnaTom, CN=fooecdsaimpca");
299         } catch (RemoteException JavaDoc re) {
300             userExists = true;
301         } catch (DuplicateKeyException JavaDoc dke) {
302             userExists = true;
303         }
304         if (userExists) {
305             log.info("User fooecdsaimpca already exists, resetting status.");
306             usersession.setUserStatus(admin,"fooecdsaimpca",UserDataConstants.STATUS_NEW);
307             log.debug("Reset status to NEW");
308         }
309         userExists = false;
310         try {
311             usersession.addUser(admin,"foorsamgf1ca","foo123","C=SE,O=AnaTom,CN=foorsamgf1ca",null,"foo@anatom.se",false,SecConst.EMPTY_ENDENTITYPROFILE,SecConst.CERTPROFILE_FIXED_ENDUSER,SecConst.USER_ENDUSER,SecConst.TOKEN_SOFT_PEM,0,rsamgf1cacaid);
312             log.debug("created user: foorsamgf1ca, foo123, C=SE, O=AnaTom, CN=foorsamgf1ca");
313         } catch (RemoteException JavaDoc re) {
314             userExists = true;
315         } catch (DuplicateKeyException JavaDoc dke) {
316             userExists = true;
317         }
318         if (userExists) {
319             log.info("User foorsamgf1ca already exists, resetting status.");
320             usersession.setUserStatus(admin,"foorsamgf1ca",UserDataConstants.STATUS_NEW);
321             log.debug("Reset status to NEW");
322         }
323
324         log.debug("<test01CreateNewUser()");
325     }
326
327     /**
328      * creates cert
329      *
330      * @throws Exception if en error occurs...
331      */

332     public void test02SignSession() throws Exception JavaDoc {
333         log.debug(">test02SignSession()");
334
335         // user that we know exists...
336
X509Certificate JavaDoc cert = (X509Certificate JavaDoc) remote.createCertificate(admin, "foo", "foo123", rsakeys.getPublic());
337         assertNotNull("Misslyckades skapa cert", cert);
338         log.debug("Cert=" + cert.toString());
339
340         try {
341             cert.verify(rsacacert.getPublicKey());
342         } catch (Exception JavaDoc e) {
343             assertTrue("Verify failed: "+e.getMessage(), false);
344         }
345         //FileOutputStream fos = new FileOutputStream("testcert.crt");
346
//fos.write(cert.getEncoded());
347
//fos.close();
348
log.debug("<test02SignSession()");
349     }
350
351     /**
352      * tests bouncy PKCS10
353      *
354      * @throws Exception if en error occurs...
355      */

356     public void test03TestBCPKCS10() throws Exception JavaDoc {
357         log.debug(">test03TestBCPKCS10()");
358         usersession.setUserStatus(admin,"foo",UserDataConstants.STATUS_NEW);
359         log.debug("Reset status of 'foo' to NEW");
360         // Create certificate request
361
PKCS10CertificationRequest req = new PKCS10CertificationRequest("SHA1WithRSA",
362                 CertTools.stringToBcX509Name("C=SE, O=AnaTom, CN=foo"), rsakeys.getPublic(), null,
363                 rsakeys.getPrivate());
364         ByteArrayOutputStream JavaDoc bOut = new ByteArrayOutputStream JavaDoc();
365         DEROutputStream dOut = new DEROutputStream(bOut);
366         dOut.writeObject(req);
367         dOut.close();
368
369         PKCS10CertificationRequest req2 = new PKCS10CertificationRequest(bOut.toByteArray());
370         boolean verify = req2.verify();
371         log.debug("Verify returned " + verify);
372         if (verify == false) {
373             log.debug("Aborting!");
374
375             return;
376         }
377         log.debug("CertificationRequest generated successfully.");
378         byte[] bcp10 = bOut.toByteArray();
379         PKCS10RequestMessage p10 = new PKCS10RequestMessage(bcp10);
380         p10.setUsername("foo");
381         p10.setPassword("foo123");
382         IResponseMessage resp = remote.createCertificate(admin,
383                 p10, Class.forName("org.ejbca.core.protocol.X509ResponseMessage"));
384         X509Certificate JavaDoc cert = CertTools.getCertfromByteArray(resp.getResponseMessage());
385         assertNotNull("Failed to create certificate", cert);
386         log.debug("Cert=" + cert.toString());
387         log.debug("<test03TestBCPKCS10()");
388     }
389
390     /**
391      * tests keytool pkcs10
392      *
393      * @throws Exception if en error occurs...
394      */

395     public void test04TestKeytoolPKCS10() throws Exception JavaDoc {
396         log.debug(">test04TestKeytoolPKCS10()");
397
398         usersession.setUserStatus(admin,"foo",UserDataConstants.STATUS_NEW);
399         log.debug("Reset status of 'foo' to NEW");
400
401         PKCS10RequestMessage p10 = new PKCS10RequestMessage(keytoolp10);
402         p10.setUsername("foo");
403         p10.setPassword("foo123");
404         IResponseMessage resp = remote.createCertificate(admin,
405                 p10, Class.forName("org.ejbca.core.protocol.X509ResponseMessage"));
406         X509Certificate JavaDoc cert = CertTools.getCertfromByteArray(resp.getResponseMessage());
407         assertNotNull("Failed to create certificate", cert);
408         log.debug("Cert=" + cert.toString());
409         log.debug("<test04TestKeytoolPKCS10()");
410     }
411
412     /**
413      * tests ie pkcs10
414      *
415      * @throws Exception if en error occurs...
416      */

417     public void test05TestIEPKCS10() throws Exception JavaDoc {
418         log.debug(">test05TestIEPKCS10()");
419
420         usersession.setUserStatus(admin,"foo",UserDataConstants.STATUS_NEW);
421         log.debug("Reset status of 'foo' to NEW");
422
423         PKCS10RequestMessage p10 = new PKCS10RequestMessage(iep10);
424         p10.setUsername("foo");
425         p10.setPassword("foo123");
426         IResponseMessage resp = remote.createCertificate(admin,
427                 p10, Class.forName("org.ejbca.core.protocol.X509ResponseMessage"));
428         X509Certificate JavaDoc cert = CertTools.getCertfromByteArray(resp.getResponseMessage());
429         assertNotNull("Failed to create certificate", cert);
430         log.debug("Cert=" + cert.toString());
431         log.debug("<test05TestIEPKCS10()");
432     }
433
434     /**
435      * test to set specific key usage
436      *
437      * @throws Exception if en error occurs...
438      */

439     public void test06KeyUsage() throws Exception JavaDoc {
440         log.debug(">test06KeyUsage()");
441
442         usersession.setUserStatus(admin,"foo",UserDataConstants.STATUS_NEW);
443         log.debug("Reset status of 'foo' to NEW");
444
445         // Create an array for KeyUsage acoording to X509Certificate.getKeyUsage()
446
boolean[] keyusage1 = new boolean[9];
447         Arrays.fill(keyusage1, false);
448         // digitalSignature
449
keyusage1[0] = true;
450         // keyEncipherment
451
keyusage1[2] = true;
452
453         X509Certificate JavaDoc cert = (X509Certificate JavaDoc) remote.createCertificate(admin, "foo", "foo123", rsakeys.getPublic(), keyusage1);
454         assertNotNull("Misslyckades skapa cert", cert);
455         log.debug("Cert=" + cert.toString());
456         boolean[] retKU = cert.getKeyUsage();
457         assertTrue("Fel KeyUsage, digitalSignature finns ej!", retKU[0]);
458         assertTrue("Fel KeyUsage, keyEncipherment finns ej!", retKU[2]);
459         assertTrue("Fel KeyUsage, cRLSign finns!", !retKU[6]);
460
461         usersession.setUserStatus(admin,"foo",UserDataConstants.STATUS_NEW);
462         log.debug("Reset status of 'foo' to NEW");
463
464         boolean[] keyusage2 = new boolean[9];
465         Arrays.fill(keyusage2, false);
466         // keyCertSign
467
keyusage2[5] = true;
468         // cRLSign
469
keyusage2[6] = true;
470
471         X509Certificate JavaDoc cert1 = (X509Certificate JavaDoc) remote.createCertificate(admin, "foo", "foo123", rsakeys.getPublic(), keyusage2);
472         assertNotNull("Misslyckades skapa cert", cert1);
473         retKU = cert1.getKeyUsage();
474         assertTrue("Fel KeyUsage, keyCertSign finns ej!", retKU[5]);
475         assertTrue("Fel KeyUsage, cRLSign finns ej!", retKU[6]);
476         assertTrue("Fel KeyUsage, digitalSignature finns!", !retKU[0]);
477
478         log.debug("Cert=" + cert1.toString());
479         log.debug("<test06KeyUsage()");
480     }
481
482     /**
483      * test DSA keys instead of RSA
484      *
485      * @throws Exception if en error occurs...
486      */

487     public void test07DSAKey() throws Exception JavaDoc {
488         log.debug(">test07DSAKey()");
489
490         usersession.setUserStatus(admin,"foo",UserDataConstants.STATUS_NEW);
491         log.debug("Reset status of 'foo' to NEW");
492
493         try {
494             PKCS10RequestMessage p10 = new PKCS10RequestMessage(keytooldsa);
495             p10.setUsername("foo");
496             p10.setPassword("foo123");
497             IResponseMessage resp = remote.createCertificate(admin,
498                     p10, Class.forName("org.ejbca.core.protocol.X509ResponseMessage"));
499             X509Certificate JavaDoc cert = CertTools.getCertfromByteArray(resp.getResponseMessage());
500             log.info("cert with DN '"+cert.getSubjectDN().getName()+"' should not be issued?");
501         } catch (Exception JavaDoc e) {
502             // RSASignSession should throw an IllegalKeyException here.
503
assertTrue("Expected IllegalKeyException: " + e.toString(),
504                     e instanceof IllegalKeyException);
505         }
506
507         log.debug("<test07DSAKey()");
508     }
509
510     /**
511      * Tests international characters
512      *
513      * @throws Exception if en error occurs...
514      */

515     public void test08SwedeChars() throws Exception JavaDoc {
516         log.debug(">test08SwedeChars()");
517         // Make user that we know...
518
boolean userExists = false;
519         try {
520             usersession.addUser(admin,"swede","foo123","C=SE, O=\u00E5\u00E4\u00F6, CN=\u00E5\u00E4\u00F6",null,"swede@anatom.se",false,SecConst.EMPTY_ENDENTITYPROFILE,SecConst.CERTPROFILE_FIXED_ENDUSER,SecConst.USER_ENDUSER,SecConst.TOKEN_SOFT_PEM,0,rsacaid);
521             log.debug("created user: swede, foo123, C=SE, O=\u00E5\u00E4\u00F6, CN=\u00E5\u00E4\u00F6");
522         } catch (RemoteException JavaDoc re) {
523             userExists = true;
524         } catch (DuplicateKeyException JavaDoc dke) {
525             userExists = true;
526         }
527         if (userExists) {
528             log.debug("user swede already exists.");
529
530             usersession.setUserStatus(admin,"swede",UserDataConstants.STATUS_NEW);
531             log.debug("Reset status to NEW");
532         }
533
534         // user that we know exists...
535
X509Certificate JavaDoc cert = (X509Certificate JavaDoc) remote.createCertificate(admin, "swede", "foo123", rsakeys.getPublic());
536         assertNotNull("Failed to create certificate", cert);
537         log.debug("Cert=" + cert.toString());
538         assertEquals("Wrong DN med swedechars", CertTools.getSubjectDN(cert),
539                 CertTools.stringToBCDNString("C=SE, O=\u00E5\u00E4\u00F6, CN=\u00E5\u00E4\u00F6"));
540         //FileOutputStream fos = new FileOutputStream("swedecert.crt");
541
//fos.write(cert.getEncoded());
542
//fos.close();
543
log.debug("<test08SwedeChars()");
544     }
545
546
547     /** Tests multiple instances of one altName
548      *
549      */

550     public void test09TestMultipleAltNames() throws Exception JavaDoc {
551         log.debug(">test09TestMultipleAltNames()");
552
553         // Create a good end entity profile (good enough), allowing multiple UPN names
554
rasession.removeEndEntityProfile(admin, "TESTMULALTNAME");
555         EndEntityProfile profile = new EndEntityProfile();
556         profile.addField(DnComponents.ORGANIZATION);
557         profile.addField(DnComponents.COUNTRY);
558         profile.addField(DnComponents.COMMONNAME);
559         profile.addField(DnComponents.UNIFORMRESOURCEID);
560         profile.addField(DnComponents.DNSNAME);
561         profile.addField(DnComponents.DNSNAME);
562         profile.addField(DnComponents.RFC822NAME);
563         profile.addField(DnComponents.IPADDRESS);
564         profile.addField(DnComponents.UPN);
565         profile.addField(DnComponents.UPN);
566         profile.setValue(EndEntityProfile.AVAILCAS,0, Integer.toString(SecConst.ALLCAS));
567         rasession.addEndEntityProfile(admin, "TESTMULALTNAME", profile);
568         int eeprofile = rasession.getEndEntityProfileId(admin, "TESTMULALTNAME");
569         try {
570             // Change a user that we know...
571
usersession.changeUser(admin, "foo", "foo123", "C=SE,O=AnaTom,CN=foo",
572                     "uniformResourceId=http://www.a.se/,upn=foo@a.se,upn=foo@b.se,rfc822name=tomas@a.se,dNSName=www.a.se,dNSName=www.b.se,iPAddress=10.1.1.1",
573                     "foo@anatom.se", false,
574                     eeprofile,
575                     SecConst.CERTPROFILE_FIXED_ENDUSER,
576                     SecConst.USER_ENDUSER,
577                     SecConst.TOKEN_SOFT_PEM, 0, UserDataConstants.STATUS_NEW, rsacaid);
578             log.debug("created user: foo, foo123, C=SE, O=AnaTom, CN=foo");
579         } catch (RemoteException JavaDoc re) {
580             assertTrue("User foo does not exist, or error changing user", false);
581         }
582         X509Certificate JavaDoc cert = (X509Certificate JavaDoc) remote.createCertificate(admin, "foo", "foo123", rsakeys.getPublic());
583         assertNotNull("Failed to create certificate", cert);
584 // FileOutputStream fos = new FileOutputStream("cert.crt");
585
// fos.write(cert.getEncoded());
586
// fos.close();
587
String JavaDoc altNames = CertTools.getSubjectAlternativeName(cert);
588         log.debug(altNames);
589         ArrayList JavaDoc list = CertTools.getPartsFromDN(altNames,CertTools.UPN);
590         assertEquals(2, list.size());
591         assertTrue(list.contains("foo@a.se"));
592         assertTrue(list.contains("foo@b.se"));
593         String JavaDoc name = CertTools.getPartFromDN(altNames,CertTools.URI);
594         assertEquals("http://www.a.se/", name);
595         name = CertTools.getPartFromDN(altNames,CertTools.EMAIL);
596         assertEquals("tomas@a.se", name);
597         list = CertTools.getPartsFromDN(altNames,CertTools.DNS);
598         assertEquals(2, list.size());
599         assertTrue(list.contains("www.a.se"));
600         assertTrue(list.contains("www.b.se"));
601         name = CertTools.getPartFromDN(altNames,CertTools.IPADDR);
602         assertEquals("10.1.1.1", name);
603
604         try {
605             // Change a user that we know...
606
usersession.changeUser(admin, "foo", "foo123", "C=SE,O=AnaTom,CN=foo",
607                     "uri=http://www.a.se/,upn=foo@a.se,upn=foo@b.se,rfc822name=tomas@a.se,dNSName=www.a.se,dNSName=www.b.se,iPAddress=10.1.1.1",
608                     "foo@anatom.se", false,
609                     eeprofile,
610                     SecConst.CERTPROFILE_FIXED_ENDUSER,
611                     SecConst.USER_ENDUSER,
612                     SecConst.TOKEN_SOFT_PEM, 0, UserDataConstants.STATUS_NEW, rsacaid);
613             log.debug("created user: foo, foo123, C=SE, O=AnaTom, CN=foo");
614         } catch (RemoteException JavaDoc re) {
615             assertTrue("User foo does not exist, or error changing user", false);
616         }
617         cert = (X509Certificate JavaDoc) remote.createCertificate(admin, "foo", "foo123", rsakeys.getPublic());
618         assertNotNull("Failed to create certificate", cert);
619 // FileOutputStream fos = new FileOutputStream("cert.crt");
620
// fos.write(cert.getEncoded());
621
// fos.close();
622
altNames = CertTools.getSubjectAlternativeName(cert);
623         log.debug(altNames);
624         list = CertTools.getPartsFromDN(altNames,CertTools.UPN);
625         assertEquals(2, list.size());
626         assertTrue(list.contains("foo@a.se"));
627         assertTrue(list.contains("foo@b.se"));
628         name = CertTools.getPartFromDN(altNames,CertTools.URI);
629         assertEquals("http://www.a.se/", name);
630         name = CertTools.getPartFromDN(altNames,CertTools.EMAIL);
631         assertEquals("tomas@a.se", name);
632         list = CertTools.getPartsFromDN(altNames,CertTools.DNS);
633         assertEquals(2, list.size());
634         assertTrue(list.contains("www.a.se"));
635         assertTrue(list.contains("www.b.se"));
636         name = CertTools.getPartFromDN(altNames,CertTools.IPADDR);
637         assertEquals("10.1.1.1", name);
638
639         // Clean up
640
rasession.removeEndEntityProfile(admin, "TESTMULALTNAME");
641
642         log.debug("<test09TestMultipleAltNames()");
643     }
644     
645     /** Tests creting a certificate with QC statement
646      *
647      */

648     public void test10TestQcCert() throws Exception JavaDoc {
649         log.debug(">test10TestQcCert()");
650
651         // Create a good certificate profile (good enough), using QC statement
652
storesession.removeCertificateProfile(admin,"TESTQC");
653         EndUserCertificateProfile certprof = new EndUserCertificateProfile();
654         certprof.setUseQCStatement(true);
655         certprof.setQCStatementRAName("rfc822Name=qc@primekey.se");
656         certprof.setUseQCEtsiQCCompliance(true);
657         certprof.setUseQCEtsiSignatureDevice(true);
658         certprof.setUseQCEtsiValueLimit(true);
659         certprof.setQCEtsiValueLimit(50000);
660         certprof.setQCEtsiValueLimitCurrency("SEK");
661         storesession.addCertificateProfile(admin, "TESTQC", certprof);
662         int cprofile = storesession.getCertificateProfileId(admin,"TESTQC");
663
664         // Create a good end entity profile (good enough), allowing multiple UPN names
665
rasession.removeEndEntityProfile(admin, "TESTQC");
666         EndEntityProfile profile = new EndEntityProfile();
667         profile.addField(DnComponents.COUNTRY);
668         profile.addField(DnComponents.COMMONNAME);
669         profile.setValue(EndEntityProfile.AVAILCAS,0, Integer.toString(SecConst.ALLCAS));
670         profile.setValue(EndEntityProfile.AVAILCERTPROFILES,0,Integer.toString(cprofile));
671         rasession.addEndEntityProfile(admin, "TESTQC", profile);
672         int eeprofile = rasession.getEndEntityProfileId(admin, "TESTQC");
673         try {
674             // Change a user that we know...
675
usersession.changeUser(admin, "foo", "foo123", "C=SE,CN=qc",
676                     null,
677                     "foo@anatom.nu", false,
678                     eeprofile,
679                     cprofile,
680                     SecConst.USER_ENDUSER,
681                     SecConst.TOKEN_SOFT_PEM, 0, UserDataConstants.STATUS_NEW, rsacaid);
682             log.debug("created user: foo, foo123, C=SE, CN=qc");
683         } catch (RemoteException JavaDoc re) {
684             assertTrue("User foo does not exist, or error changing user", false);
685         }
686         X509Certificate JavaDoc cert = (X509Certificate JavaDoc) remote.createCertificate(admin, "foo", "foo123", rsakeys.getPublic());
687         assertNotNull("Failed to create certificate", cert);
688 // FileOutputStream fos = new FileOutputStream("cert.crt");
689
// fos.write(cert.getEncoded());
690
// fos.close();
691
String JavaDoc dn = cert.getSubjectDN().getName();
692         assertEquals(CertTools.stringToBCDNString("cn=qc,c=SE"), CertTools.stringToBCDNString(dn));
693         assertEquals("rfc822name=qc@primekey.se", QCStatementExtension.getQcStatementAuthorities(cert));
694         Collection JavaDoc ids = QCStatementExtension.getQcStatementIds(cert);
695         assertTrue(ids.contains(RFC3739QCObjectIdentifiers.id_qcs_pkixQCSyntax_v1.getId()));
696         assertTrue(ids.contains(ETSIQCObjectIdentifiers.id_etsi_qcs_QcCompliance.getId()));
697         assertTrue(ids.contains(ETSIQCObjectIdentifiers.id_etsi_qcs_QcSSCD.getId()));
698         assertTrue(ids.contains(ETSIQCObjectIdentifiers.id_etsi_qcs_LimiteValue.getId()));
699         String JavaDoc limit = QCStatementExtension.getQcStatementValueLimit(cert);
700         assertEquals("50000 SEK", limit);
701
702         // Clean up
703
rasession.removeEndEntityProfile(admin, "TESTQC");
704         storesession.removeCertificateProfile(admin,"TESTQC");
705
706         log.debug("<test10TestQcCert()");
707     }
708
709     /** Tests creting a certificate with QC statement
710      *
711      */

712     public void test11TestValidityOverride() throws Exception JavaDoc {
713         log.debug(">test11TestValidityOverride()");
714
715         // Create a good certificate profile (good enough), using QC statement
716
storesession.removeCertificateProfile(admin,"TESTVALOVERRIDE");
717         EndUserCertificateProfile certprof = new EndUserCertificateProfile();
718         certprof.setAllowValidityOverride(false);
719         certprof.setValidity(298);
720         storesession.addCertificateProfile(admin, "TESTVALOVERRIDE", certprof);
721         int cprofile = storesession.getCertificateProfileId(admin,"TESTVALOVERRIDE");
722
723         // Create a good end entity profile (good enough), allowing multiple UPN names
724
rasession.removeEndEntityProfile(admin, "TESTVALOVERRIDE");
725         EndEntityProfile profile = new EndEntityProfile();
726         profile.addField(DnComponents.COUNTRY);
727         profile.addField(DnComponents.COMMONNAME);
728         profile.setValue(EndEntityProfile.AVAILCAS,0, Integer.toString(SecConst.ALLCAS));
729         profile.setValue(EndEntityProfile.AVAILCERTPROFILES,0,Integer.toString(cprofile));
730         rasession.addEndEntityProfile(admin, "TESTVALOVERRIDE", profile);
731         int eeprofile = rasession.getEndEntityProfileId(admin, "TESTVALOVERRIDE");
732         try {
733             // Change a user that we know...
734
usersession.changeUser(admin, "foo", "foo123", "C=SE,CN=validityoverride",
735                     null,
736                     "foo@anatom.nu", false,
737                     eeprofile,
738                     cprofile,
739                     SecConst.USER_ENDUSER,
740                     SecConst.TOKEN_SOFT_PEM, 0, UserDataConstants.STATUS_NEW, rsacaid);
741             log.debug("created user: foo, foo123, C=SE, CN=validityoverride");
742         } catch (RemoteException JavaDoc re) {
743             assertTrue("User foo does not exist, or error changing user", false);
744         }
745         Calendar JavaDoc cal = Calendar.getInstance();
746         cal.add(Calendar.DAY_OF_MONTH, 10);
747         X509Certificate JavaDoc cert = (X509Certificate JavaDoc) remote.createCertificate(admin, "foo", "foo123", rsakeys.getPublic(), -1, null, cal.getTime());
748         assertNotNull("Failed to create certificate", cert);
749         String JavaDoc dn = cert.getSubjectDN().getName();
750         assertEquals(CertTools.stringToBCDNString("cn=validityoverride,c=SE"), CertTools.stringToBCDNString(dn));
751         Date JavaDoc notAfter = cert.getNotAfter();
752         cal = Calendar.getInstance();
753         cal.add(Calendar.DAY_OF_MONTH, 297);
754         // Override was not enabled, the cert should have notAfter more than 3064 days in the future (3065 to be exact)
755
assertTrue(notAfter.compareTo(cal.getTime()) > 0);
756         cal.add(Calendar.DAY_OF_MONTH, 2);
757         // Override was not enabled, the cert should have notAfter more than 3064 days in the future (3065 to be exact)
758
assertTrue(notAfter.compareTo(cal.getTime()) < 0);
759         
760         // Change so that we allow override of validity time
761
CertificateProfile prof = storesession.getCertificateProfile(admin,cprofile);
762         prof.setAllowValidityOverride(true);
763         prof.setValidity(3065);
764         storesession.changeCertificateProfile(admin, "TESTVALOVERRIDE", prof);
765         cal = Calendar.getInstance();
766         Calendar JavaDoc notBefore = Calendar.getInstance();
767         notBefore.add(Calendar.DAY_OF_MONTH, 2);
768         cal.add(Calendar.DAY_OF_MONTH, 10);
769         usersession.setUserStatus(admin, "foo", UserDataConstants.STATUS_NEW);
770         cert = (X509Certificate JavaDoc) remote.createCertificate(admin, "foo", "foo123", rsakeys.getPublic(), -1, notBefore.getTime(), cal.getTime());
771         assertNotNull("Failed to create certificate", cert);
772         assertEquals(CertTools.stringToBCDNString("cn=validityoverride,c=SE"), CertTools.stringToBCDNString(dn));
773         notAfter = cert.getNotAfter();
774         cal = Calendar.getInstance();
775         cal.add(Calendar.DAY_OF_MONTH, 11);
776         // Override was enabled, the cert should have notAfter less than 11 days in the future (10 to be exact)
777
assertTrue(notAfter.compareTo(cal.getTime()) < 0);
778         notAfter= cert.getNotBefore();
779         cal = Calendar.getInstance();
780         cal.add(Calendar.DAY_OF_MONTH, 1);
781         // Override was enabled, the cert should have notBefore more than 1 days in the future (2 to be exact)
782
assertTrue(notAfter.compareTo(cal.getTime()) > 0);
783         cal.add(Calendar.DAY_OF_MONTH, 2);
784         assertTrue(notAfter.compareTo(cal.getTime()) < 0);
785         
786         
787
788         // Clean up
789
rasession.removeEndEntityProfile(admin, "TESTVALOVERRIDE");
790         storesession.removeCertificateProfile(admin,"TESTVALOVERRIDE");
791
792         log.debug("<test11TestValidityOverride()");
793     }
794
795     /**
796      * creates cert
797      *
798      * @throws Exception if en error occurs...
799      */

800     public void test12SignSessionECDSAWithRSACA() throws Exception JavaDoc {
801         log.debug(">test12SignSessionECDSAWithRSACA()");
802
803         usersession.setUserStatus(admin,"foo",UserDataConstants.STATUS_NEW);
804         log.debug("Reset status of 'foo' to NEW");
805         // user that we know exists...
806
X509Certificate JavaDoc selfcert = CertTools.genSelfCert("CN=selfsigned", 1, null, ecdsakeys.getPrivate(), ecdsakeys.getPublic(), CATokenConstants.SIGALG_SHA256_WITH_ECDSA, false);
807         X509Certificate JavaDoc cert = (X509Certificate JavaDoc) remote.createCertificate(admin, "foo", "foo123", selfcert);
808         assertNotNull("Misslyckades skapa cert", cert);
809         log.debug("Cert=" + cert.toString());
810         PublicKey JavaDoc pk = cert.getPublicKey();
811         if (pk instanceof JCEECPublicKey) {
812             JCEECPublicKey ecpk = (JCEECPublicKey) pk;
813             assertEquals(ecpk.getAlgorithm(), "EC");
814             org.bouncycastle.jce.spec.ECParameterSpec spec = ecpk.getParameters();
815             assertNotNull("ImplicitlyCA must have null spec", spec);
816         } else {
817             assertTrue("Public key is not EC", false);
818         }
819         try {
820             cert.verify(rsacacert.getPublicKey());
821         } catch (Exception JavaDoc e) {
822             assertTrue("Verify failed: "+e.getMessage(), false);
823         }
824
825         //FileOutputStream fos = new FileOutputStream("testcert.crt");
826
//fos.write(cert.getEncoded());
827
//fos.close();
828
log.debug("<test12SignSessionECDSAWithRSACA()");
829     }
830
831     /**
832      * tests bouncy PKCS10
833      *
834      * @throws Exception if en error occurs...
835      */

836     public void test13TestBCPKCS10ECDSAWithRSACA() throws Exception JavaDoc {
837         log.debug(">test13TestBCPKCS10ECDSAWithRSACA()");
838         usersession.setUserStatus(admin,"foo",UserDataConstants.STATUS_NEW);
839         log.debug("Reset status of 'foo' to NEW");
840         // Create certificate request
841
PKCS10CertificationRequest req = new PKCS10CertificationRequest("SHA256WithECDSA",
842                 CertTools.stringToBcX509Name("C=SE, O=AnaTom, CN=foo"), ecdsakeys.getPublic(), null,
843                 ecdsakeys.getPrivate());
844         ByteArrayOutputStream JavaDoc bOut = new ByteArrayOutputStream JavaDoc();
845         DEROutputStream dOut = new DEROutputStream(bOut);
846         dOut.writeObject(req);
847         dOut.close();
848
849         PKCS10CertificationRequest req2 = new PKCS10CertificationRequest(bOut.toByteArray());
850         boolean verify = req2.verify();
851         log.debug("Verify returned " + verify);
852         if (verify == false) {
853             log.debug("Aborting!");
854             return;
855         }
856         log.debug("CertificationRequest generated successfully.");
857         byte[] bcp10 = bOut.toByteArray();
858         PKCS10RequestMessage p10 = new PKCS10RequestMessage(bcp10);
859         p10.setUsername("foo");
860         p10.setPassword("foo123");
861         IResponseMessage resp = remote.createCertificate(admin,
862                 p10, Class.forName("org.ejbca.core.protocol.X509ResponseMessage"));
863         X509Certificate JavaDoc cert = CertTools.getCertfromByteArray(resp.getResponseMessage());
864         assertNotNull("Failed to create certificate", cert);
865         log.debug("Cert=" + cert.toString());
866         PublicKey JavaDoc pk = cert.getPublicKey();
867         if (pk instanceof JCEECPublicKey) {
868             JCEECPublicKey ecpk = (JCEECPublicKey) pk;
869             assertEquals(ecpk.getAlgorithm(), "EC");
870             org.bouncycastle.jce.spec.ECParameterSpec spec = ecpk.getParameters();
871             assertNotNull("ImplicitlyCA must have null spec", spec);
872         } else {
873             assertTrue("Public key is not EC", false);
874         }
875         try {
876             cert.verify(rsacacert.getPublicKey());
877         } catch (Exception JavaDoc e) {
878             assertTrue("Verify failed: "+e.getMessage(), false);
879         }
880         log.debug("<test13TestBCPKCS10ECDSAWithRSACA()");
881     }
882
883     /**
884      * creates cert
885      *
886      * @throws Exception if en error occurs...
887      */

888     public void test14SignSessionECDSAWithECDSACA() throws Exception JavaDoc {
889         log.debug(">test14SignSessionECDSAWithECDSACA()");
890
891         usersession.setUserStatus(admin,"fooecdsa",UserDataConstants.STATUS_NEW);
892         log.debug("Reset status of 'fooecdsa' to NEW");
893         // user that we know exists...
894
X509Certificate JavaDoc selfcert = CertTools.genSelfCert("CN=selfsigned", 1, null, ecdsakeys.getPrivate(), ecdsakeys.getPublic(), CATokenConstants.SIGALG_SHA256_WITH_ECDSA, false);
895         X509Certificate JavaDoc cert = (X509Certificate JavaDoc) remote.createCertificate(admin, "fooecdsa", "foo123", selfcert);
896         assertNotNull("Misslyckades skapa cert", cert);
897         log.debug("Cert=" + cert.toString());
898         PublicKey JavaDoc pk = cert.getPublicKey();
899         if (pk instanceof JCEECPublicKey) {
900             JCEECPublicKey ecpk = (JCEECPublicKey) pk;
901             assertEquals(ecpk.getAlgorithm(), "EC");
902             org.bouncycastle.jce.spec.ECParameterSpec spec = ecpk.getParameters();
903             assertNotNull("ImplicitlyCA must have null spec", spec);
904         } else {
905             assertTrue("Public key is not EC", false);
906         }
907         try {
908             cert.verify(ecdsacacert.getPublicKey());
909         } catch (Exception JavaDoc e) {
910             assertTrue("Verify failed: "+e.getMessage(), false);
911         }
912
913         //FileOutputStream fos = new FileOutputStream("testcert.crt");
914
//fos.write(cert.getEncoded());
915
//fos.close();
916
log.debug("<test14SignSessionECDSAWithECDSACA()");
917     }
918
919     /**
920      * tests bouncy PKCS10
921      *
922      * @throws Exception if en error occurs...
923      */

924     public void test15TestBCPKCS10ECDSAWithECDSACA() throws Exception JavaDoc {
925         log.debug(">test15TestBCPKCS10ECDSAWithECDSACA()");
926         usersession.setUserStatus(admin,"fooecdsa",UserDataConstants.STATUS_NEW);
927         log.debug("Reset status of 'foo' to NEW");
928         // Create certificate request
929
PKCS10CertificationRequest req = new PKCS10CertificationRequest("SHA256WithECDSA",
930                 CertTools.stringToBcX509Name("C=SE, O=AnaTom, CN=fooecdsa"), ecdsakeys.getPublic(), null,
931                 ecdsakeys.getPrivate());
932         ByteArrayOutputStream JavaDoc bOut = new ByteArrayOutputStream JavaDoc();
933         DEROutputStream dOut = new DEROutputStream(bOut);
934         dOut.writeObject(req);
935         dOut.close();
936
937         PKCS10CertificationRequest req2 = new PKCS10CertificationRequest(bOut.toByteArray());
938         boolean verify = req2.verify();
939         log.debug("Verify returned " + verify);
940         if (verify == false) {
941             log.debug("Aborting!");
942             return;
943         }
944         log.debug("CertificationRequest generated successfully.");
945         byte[] bcp10 = bOut.toByteArray();
946         PKCS10RequestMessage p10 = new PKCS10RequestMessage(bcp10);
947         p10.setUsername("fooecdsa");
948         p10.setPassword("foo123");
949         IResponseMessage resp = remote.createCertificate(admin,
950                 p10, Class.forName("org.ejbca.core.protocol.X509ResponseMessage"));
951         X509Certificate JavaDoc cert = CertTools.getCertfromByteArray(resp.getResponseMessage());
952         assertNotNull("Failed to create certificate", cert);
953         log.debug("Cert=" + cert.toString());
954         PublicKey JavaDoc pk = cert.getPublicKey();
955         if (pk instanceof JCEECPublicKey) {
956             JCEECPublicKey ecpk = (JCEECPublicKey) pk;
957             assertEquals(ecpk.getAlgorithm(), "EC");
958             org.bouncycastle.jce.spec.ECParameterSpec spec = ecpk.getParameters();
959             assertNotNull("ImplicitlyCA must have null spec", spec);
960         } else {
961             assertTrue("Public key is not EC", false);
962         }
963         try {
964             cert.verify(ecdsacacert.getPublicKey());
965         } catch (Exception JavaDoc e) {
966             assertTrue("Verify failed: "+e.getMessage(), false);
967         }
968         log.debug("<test15TestBCPKCS10ECDSAWithECDSACA()");
969     }
970     /**
971      * creates cert
972      *
973      * @throws Exception if en error occurs...
974      */

975     public void test16SignSessionECDSAWithECDSAImplicitlyCACA() throws Exception JavaDoc {
976         log.debug(">test16SignSessionECDSAWithECDSAImplicitlyCACA()");
977
978         usersession.setUserStatus(admin,"fooecdsaimpca",UserDataConstants.STATUS_NEW);
979         log.debug("Reset status of 'fooecdsaimpca' to NEW");
980         // user that we know exists...
981
X509Certificate JavaDoc selfcert = CertTools.genSelfCert("CN=selfsigned", 1, null, ecdsakeys.getPrivate(), ecdsakeys.getPublic(), CATokenConstants.SIGALG_SHA256_WITH_ECDSA, false);
982         X509Certificate JavaDoc cert = (X509Certificate JavaDoc) remote.createCertificate(admin, "fooecdsaimpca", "foo123", selfcert);
983         assertNotNull("Misslyckades skapa cert", cert);
984         log.debug("Cert=" + cert.toString());
985         PublicKey JavaDoc pk = cert.getPublicKey();
986         if (pk instanceof JCEECPublicKey) {
987             JCEECPublicKey ecpk = (JCEECPublicKey) pk;
988             assertEquals(ecpk.getAlgorithm(), "EC");
989             org.bouncycastle.jce.spec.ECParameterSpec spec = ecpk.getParameters();
990             assertNotNull("ImplicitlyCA must have null spec", spec);
991         } else {
992             assertTrue("Public key is not EC", false);
993         }
994         try {
995             cert.verify(ecdsaimplicitlycacacert.getPublicKey());
996         } catch (Exception JavaDoc e) {
997             assertTrue("Verify failed: "+e.getMessage(), false);
998         }
999
1000        //FileOutputStream fos = new FileOutputStream("testcert.crt");
1001
//fos.write(cert.getEncoded());
1002
//fos.close();
1003
log.debug("<test16SignSessionECDSAWithECDSAImplicitlyCACA()");
1004    }
1005
1006    /**
1007     * tests bouncy PKCS10
1008     *
1009     * @throws Exception if en error occurs...
1010     */

1011    public void test17TestBCPKCS10ECDSAWithECDSAImplicitlyCACA() throws Exception JavaDoc {
1012        log.debug(">test17TestBCPKCS10ECDSAWithECDSAImplicitlyCACA()");
1013        usersession.setUserStatus(admin,"fooecdsaimpca",UserDataConstants.STATUS_NEW);
1014        log.debug("Reset status of 'foo' to NEW");
1015        // Create certificate request
1016
PKCS10CertificationRequest req = new PKCS10CertificationRequest("SHA256WithECDSA",
1017                CertTools.stringToBcX509Name("C=SE, O=AnaTom, CN=fooecdsaimpca"), ecdsakeys.getPublic(), null,
1018                ecdsakeys.getPrivate());
1019        ByteArrayOutputStream JavaDoc bOut = new ByteArrayOutputStream JavaDoc();
1020        DEROutputStream dOut = new DEROutputStream(bOut);
1021        dOut.writeObject(req);
1022        dOut.close();
1023
1024        PKCS10CertificationRequest req2 = new PKCS10CertificationRequest(bOut.toByteArray());
1025        boolean verify = req2.verify();
1026        log.debug("Verify returned " + verify);
1027        if (verify == false) {
1028            log.debug("Aborting!");
1029            return;
1030        }
1031        log.debug("CertificationRequest generated successfully.");
1032        byte[] bcp10 = bOut.toByteArray();
1033        PKCS10RequestMessage p10 = new PKCS10RequestMessage(bcp10);
1034        p10.setUsername("fooecdsaimpca");
1035        p10.setPassword("foo123");
1036        IResponseMessage resp = remote.createCertificate(admin,
1037                p10, Class.forName("org.ejbca.core.protocol.X509ResponseMessage"));
1038        X509Certificate JavaDoc cert = CertTools.getCertfromByteArray(resp.getResponseMessage());
1039        assertNotNull("Failed to create certificate", cert);
1040        log.debug("Cert=" + cert.toString());
1041        PublicKey JavaDoc pk = cert.getPublicKey();
1042        if (pk instanceof JCEECPublicKey) {
1043            JCEECPublicKey ecpk = (JCEECPublicKey) pk;
1044            assertEquals(ecpk.getAlgorithm(), "EC");
1045            org.bouncycastle.jce.spec.ECParameterSpec spec = ecpk.getParameters();
1046            assertNotNull("ImplicitlyCA must have null spec", spec);
1047        } else {
1048            assertTrue("Public key is not EC", false);
1049        }
1050        try {
1051            cert.verify(ecdsaimplicitlycacacert.getPublicKey());
1052        } catch (Exception JavaDoc e) {
1053            assertTrue("Verify failed: "+e.getMessage(), false);
1054        }
1055        log.debug("<test17TestBCPKCS10ECDSAWithECDSAImplicitlyCACA()");
1056    }
1057
1058    /**
1059     * creates cert
1060     *
1061     * @throws Exception if en error occurs...
1062     */

1063    public void test18SignSessionRSAMGF1WithRSASha256WithMGF1CA() throws Exception JavaDoc {
1064        log.debug(">test18SignSessionRSAWithRSASha256WithMGF1CA()");
1065
1066        usersession.setUserStatus(admin,"foorsamgf1ca",UserDataConstants.STATUS_NEW);
1067        log.debug("Reset status of 'foorsamgf1ca' to NEW");
1068        // user that we know exists...
1069
X509Certificate JavaDoc selfcert = CertTools.genSelfCert("CN=selfsigned", 1, null, rsakeys.getPrivate(), rsakeys.getPublic(), CATokenConstants.SIGALG_SHA256_WITH_RSA_AND_MGF1, false);
1070        try {
1071        selfcert.verify(selfcert.getPublicKey());
1072        } catch (Exception JavaDoc e) {
1073            e.printStackTrace();
1074            assertTrue(false);
1075        }
1076        X509Certificate JavaDoc retcert = (X509Certificate JavaDoc) remote.createCertificate(admin, "foorsamgf1ca", "foo123", selfcert);
1077        // RSA with MGF1 is not supported by sun, so we must transfer this (serialized) cert to a BC cert
1078
X509Certificate JavaDoc cert = CertTools.getCertfromByteArray(retcert.getEncoded());
1079        assertNotNull("Failed to create certificate", cert);
1080        log.debug("Cert=" + cert.toString());
1081// FileOutputStream fos = new FileOutputStream("/tmp/testcert.crt");
1082
// fos.write(cert.getEncoded());
1083
// fos.close();
1084
PublicKey JavaDoc pk = cert.getPublicKey();
1085        if (pk instanceof RSAPublicKey JavaDoc) {
1086            RSAPublicKey JavaDoc rsapk = (RSAPublicKey JavaDoc) pk;
1087            assertEquals(rsapk.getAlgorithm(), "RSA");
1088        } else {
1089            assertTrue("Public key is not RSA", false);
1090        }
1091        try {
1092            cert.verify(rsamgf1cacacert.getPublicKey());
1093        } catch (Exception JavaDoc e) {
1094            //e.printStackTrace();
1095
assertTrue("Verify failed: "+e.getMessage(), false);
1096        }
1097        // 1.2.840.113549.1.1.10 is SHA256WithRSAAndMGF1
1098
assertEquals("1.2.840.113549.1.1.10", cert.getSigAlgOID());
1099        assertEquals("1.2.840.113549.1.1.10", cert.getSigAlgName());
1100        assertEquals("1.2.840.113549.1.1.10", rsamgf1cacacert.getSigAlgOID());
1101        assertEquals("1.2.840.113549.1.1.10", rsamgf1cacacert.getSigAlgName());
1102        
1103        log.debug("<test18SignSessionRSAWithRSASha256WithMGF1CA()");
1104    }
1105
1106    /**
1107     * tests bouncy PKCS10
1108     *
1109     * @throws Exception if en error occurs...
1110     */

1111    public void test19TestBCPKCS10RSAWithRSASha256WithMGF1CA() throws Exception JavaDoc {
1112        log.debug(">test19TestBCPKCS10RSAWithRSASha256WithMGF1CA()");
1113        usersession.setUserStatus(admin,"foorsamgf1ca",UserDataConstants.STATUS_NEW);
1114        log.debug("Reset status of 'foorsamgf1ca' to NEW");
1115        // Create certificate request
1116
PKCS10CertificationRequest req = new PKCS10CertificationRequest(CATokenConstants.SIGALG_SHA256_WITH_RSA_AND_MGF1,
1117                CertTools.stringToBcX509Name("C=SE, O=AnaTom, CN=foorsamgf1ca"), rsakeys.getPublic(), null,
1118                rsakeys.getPrivate());
1119        ByteArrayOutputStream JavaDoc bOut = new ByteArrayOutputStream JavaDoc();
1120        DEROutputStream dOut = new DEROutputStream(bOut);
1121        dOut.writeObject(req);
1122        dOut.close();
1123
1124        PKCS10CertificationRequest req2 = new PKCS10CertificationRequest(bOut.toByteArray());
1125        boolean verify = req2.verify();
1126        log.debug("Verify returned " + verify);
1127        if (verify == false) {
1128            log.debug("Aborting!");
1129            return;
1130        }
1131        log.debug("CertificationRequest generated successfully.");
1132        byte[] bcp10 = bOut.toByteArray();
1133        PKCS10RequestMessage p10 = new PKCS10RequestMessage(bcp10);
1134        p10.setUsername("foorsamgf1ca");
1135        p10.setPassword("foo123");
1136        IResponseMessage resp = remote.createCertificate(admin,
1137                p10, Class.forName("org.ejbca.core.protocol.X509ResponseMessage"));
1138        X509Certificate JavaDoc cert = CertTools.getCertfromByteArray(resp.getResponseMessage());
1139        //X509Certificate cert = CertTools.getCertfromByteArray(retcert.getEncoded());
1140
assertNotNull("Failed to create certificate", cert);
1141        log.debug("Cert=" + cert.toString());
1142// FileOutputStream fos = new FileOutputStream("/tmp/testcert1.crt");
1143
// fos.write(cert.getEncoded());
1144
// fos.close();
1145
PublicKey JavaDoc pk = cert.getPublicKey();
1146        if (pk instanceof RSAPublicKey JavaDoc) {
1147            RSAPublicKey JavaDoc rsapk = (RSAPublicKey JavaDoc) pk;
1148            assertEquals(rsapk.getAlgorithm(), "RSA");
1149        } else {
1150            assertTrue("Public key is not RSA", false);
1151        }
1152        try {
1153            cert.verify(rsamgf1cacacert.getPublicKey());
1154        } catch (Exception JavaDoc e) {
1155            assertTrue("Verify failed: "+e.getMessage(), false);
1156        }
1157        // 1.2.840.113549.1.1.10 is SHA256WithRSAAndMGF1
1158
assertEquals("1.2.840.113549.1.1.10", cert.getSigAlgOID());
1159        assertEquals("1.2.840.113549.1.1.10", cert.getSigAlgName());
1160        assertEquals("1.2.840.113549.1.1.10", rsamgf1cacacert.getSigAlgOID());
1161        assertEquals("1.2.840.113549.1.1.10", rsamgf1cacacert.getSigAlgName());
1162
1163        log.debug("<test19TestBCPKCS10RSAWithRSASha256WithMGF1CA()");
1164    }
1165
1166    /**
1167     * creates new user
1168     *
1169     * @throws Exception if en error occurs...
1170     */

1171    public void test99DeleteUsers() throws Exception JavaDoc {
1172        log.debug(">test99DeleteUsers()");
1173
1174        // delete users that we know...
1175
usersession.deleteUser(admin, "foo");
1176        log.debug("deleted user: foo, foo123, C=SE, O=AnaTom, CN=foo");
1177        usersession.deleteUser(admin, "fooecdsa");
1178        log.debug("deleted user: fooecdsa, foo123, C=SE, O=AnaTom, CN=foo");
1179        usersession.deleteUser(admin, "fooecdsaimpca");
1180        log.debug("deleted user: fooecdsaimpca, foo123, C=SE, O=AnaTom, CN=foo");
1181
1182        log.debug("<test99DeleteUsers()");
1183    }
1184    
1185    
1186    /**
1187     * Tests scep message
1188     */

1189/*
1190    public void test10TestOpenScep() throws Exception {
1191        log.debug(">test10TestOpenScep()");
1192        UserDataPK pk = new UserDataPK("foo");
1193        UserDataRemote data = userhome.findByPrimaryKey(pk);
1194        data.setStatus(UserDataRemote.STATUS_NEW);
1195        log.debug("Reset status of 'foo' to NEW");
1196        IResponseMessage resp = remote.createCertificate(admin, new ScepRequestMessage(openscep), -1, Class.forName("org.ejbca.core.protocol.ScepResponseMessage"));
1197        assertNotNull("Failed to create certificate", resp);
1198        byte[] msg = resp.getResponseMessage();
1199        log.debug("Message: "+new String(Base64.encode(msg,true)));
1200        assertNotNull("Failed to get encoded response message", msg);
1201        log.debug("<test10TestOpenScep()");
1202    }
1203*/

1204}
1205
Popular Tags