1/*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements.  See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18package org.apache.harmony.security.tests.java.security;
19
20import java.io.ByteArrayInputStream;
21import java.io.InputStream;
22import java.io.OutputStream;
23import java.security.Certificate;
24import java.security.Identity;
25import java.security.IdentityScope;
26import java.security.KeyManagementException;
27import java.security.KeyPairGenerator;
28import java.security.Principal;
29import java.security.PublicKey;
30import java.security.cert.CertificateFactory;
31import java.security.cert.X509Certificate;
32import org.apache.harmony.security.tests.java.security.IdentityScope2Test.IdentityScopeSubclass;
33
34@SuppressWarnings("deprecation")
35public class Identity2Test extends junit.framework.TestCase {
36
37    private static PublicKey PUB_KEY;
38    private static PublicKey getPubKey() throws Exception {
39        if (PUB_KEY == null) {
40            PUB_KEY = KeyPairGenerator.getInstance("DSA").genKeyPair().getPublic();
41        }
42        return PUB_KEY;
43    }
44
45    public static class CertificateImpl implements java.security.Certificate {
46
47        X509Certificate cert;
48
49        public CertificateImpl(X509Certificate cert) {
50            this.cert = cert;
51        }
52
53        public Principal getGuarantor() {
54            return cert.getIssuerDN();
55        }
56
57        public void encode(OutputStream out) {
58        }
59
60        public void decode(InputStream in) {
61        }
62
63        public String toString() {
64            return "";
65        }
66
67        public String toString(boolean b) {
68            return "";
69        }
70
71        public String getFormat() {
72            return cert.getType();
73        }
74
75        public Principal getPrincipal() {
76            return cert.getSubjectDN();
77        }
78
79        public PublicKey getPublicKey() {
80            return cert.getPublicKey();
81        }
82    }
83
84    String certificate = "-----BEGIN CERTIFICATE-----\n"
85            + "MIICZTCCAdICBQL3AAC2MA0GCSqGSIb3DQEBAgUAMF8xCzAJBgNVBAYTAlVTMSAw\n"
86            + "HgYDVQQKExdSU0EgRGF0YSBTZWN1cml0eSwgSW5jLjEuMCwGA1UECxMlU2VjdXJl\n"
87            + "IFNlcnZlciBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw05NzAyMjAwMDAwMDBa\n"
88            + "Fw05ODAyMjAyMzU5NTlaMIGWMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZv\n"
89            + "cm5pYTESMBAGA1UEBxMJUGFsbyBBbHRvMR8wHQYDVQQKExZTdW4gTWljcm9zeXN0\n"
90            + "ZW1zLCBJbmMuMSEwHwYDVQQLExhUZXN0IGFuZCBFdmFsdWF0aW9uIE9ubHkxGjAY\n"
91            + "BgNVBAMTEWFyZ29uLmVuZy5zdW4uY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCB\n"
92            + "iQKBgQCofmdY+PiUWN01FOzEewf+GaG+lFf132UpzATmYJkA4AEA/juW7jSi+LJk\n"
93            + "wJKi5GO4RyZoyimAL/5yIWDV6l1KlvxyKslr0REhMBaD/3Z3EsLTTEf5gVrQS6sT\n"
94            + "WMoSZAyzB39kFfsB6oUXNtV8+UKKxSxKbxvhQn267PeCz5VX2QIDAQABMA0GCSqG\n"
95            + "SIb3DQEBAgUAA34AXl3at6luiV/7I9MN5CXYoPJYI8Bcdc1hBagJvTMcmlqL2uOZ\n"
96            + "H9T5hNMEL9Tk6aI7yZPXcw/xI2K6pOR/FrMp0UwJmdxX7ljV6ZtUZf7pY492UqwC\n"
97            + "1777XQ9UEZyrKJvF5ntleeO0ayBqLGVKCWzWZX9YsXCpv47FNLZbupE=\n"
98            + "-----END CERTIFICATE-----\n";
99
100    ByteArrayInputStream certArray = new ByteArrayInputStream(certificate.getBytes());
101
102    String certificate2 = "-----BEGIN CERTIFICATE-----\n"
103            + "MIICZzCCAdCgAwIBAgIBGzANBgkqhkiG9w0BAQUFADBhMQswCQYDVQQGEwJVUzEY\n"
104            + "MBYGA1UEChMPVS5TLiBHb3Zlcm5tZW50MQwwCgYDVQQLEwNEb0QxDDAKBgNVBAsT\n"
105            + "A1BLSTEcMBoGA1UEAxMTRG9EIFBLSSBNZWQgUm9vdCBDQTAeFw05ODA4MDMyMjAy\n"
106            + "MjlaFw0wODA4MDQyMjAyMjlaMGExCzAJBgNVBAYTAlVTMRgwFgYDVQQKEw9VLlMu\n"
107            + "IEdvdmVybm1lbnQxDDAKBgNVBAsTA0RvRDEMMAoGA1UECxMDUEtJMRwwGgYDVQQD\n"
108            + "ExNEb0QgUEtJIE1lZCBSb290IENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB\n"
109            + "gQDbrM/J9FrJSX+zxFUbsI9Vw5QbguVBIa95rwW/0M8+sM0r5gd+DY6iubm6wnXk\n"
110            + "CSvbfQlFEDSKr4WYeeGp+d9WlDnQdtDFLdA45tCi5SHjnW+hGAmZnld0rz6wQekF\n"
111            + "5xQaa5A6wjhMlLOjbh27zyscrorMJ1O5FBOWnEHcRv6xqQIDAQABoy8wLTAdBgNV\n"
112            + "HQ4EFgQUVrmYR6m9701cHQ3r5kXyG7zsCN0wDAYDVR0TBAUwAwEB/zANBgkqhkiG\n"
113            + "9w0BAQUFAAOBgQDVX1Y0YqC7vekeZjVxtyuC8Mnxbrz6D109AX07LEIRzNYzwZ0w\n"
114            + "MTImSp9sEzWW+3FueBIU7AxGys2O7X0qmN3zgszPfSiocBuQuXIYQctJhKjF5KVc\n"
115            + "VGQRYYlt+myhl2vy6yPzEVCjiKwMEb1Spu0irCf+lFW2hsdjvmSQMtZvOw==\n"
116            + "-----END CERTIFICATE-----\n";
117
118    ByteArrayInputStream certArray2 = new ByteArrayInputStream(certificate2.getBytes());
119
120
121    public static class IdentitySubclass extends Identity {
122        private static final long serialVersionUID = 1L;
123
124        public IdentitySubclass() {
125            super();
126        }
127
128        public IdentitySubclass(String name) {
129            super(name);
130        }
131
132        public IdentitySubclass(String name, IdentityScope scope)
133                throws KeyManagementException {
134            super(name, scope);
135        }
136    }
137
138    /**
139     * java.security.Identity#Identity()
140     */
141    public void test_Constructor() {
142        new IdentitySubclass();
143    }
144
145    /**
146     * java.security.Identity#Identity(java.lang.String)
147     */
148    public void test_ConstructorLjava_lang_String() {
149        String[] str = {"test", "", null};
150        IdentitySubclass is;
151        for (int i = 0; i < str.length; i++) {
152            try {
153                is = new IdentitySubclass(str[i]);
154                assertNotNull(is);
155                assertTrue(is instanceof Identity);
156            } catch (Exception e) {
157                fail("Unexpected exception for Identity(java.lang.String) with parameter "
158                     + str[i]);
159            }
160        }
161    }
162
163    /**
164     * java.security.Identity#Identity(java.lang.String,
165     *        java.security.IdentityScope)
166     */
167    public void test_ConstructorLjava_lang_StringLjava_security_IdentityScope() throws Exception {
168        String nameNull = null;
169        String[] str = {"test", "", "!@#$%^&*()", "identity name"};
170        IdentityScopeSubclass iss = new IdentityScopeSubclass("name");
171        IdentitySubclass is;
172
173        for (int i = 0; i < str.length; i++) {
174            try {
175                is = new IdentitySubclass(str[i], new IdentityScopeSubclass());
176                assertNotNull(is);
177                assertTrue(is instanceof Identity);
178            } catch (Exception e) {
179                System.out.println(e);
180                fail("Unexpected exception for parameter " + str[i]);
181            }
182        }
183
184        try {
185            is = new IdentitySubclass(nameNull, new IdentityScopeSubclass());
186        } catch (NullPointerException npe) {
187        } catch (Exception e) {
188            fail("Incorrect exception " + e + " was thrown");
189        }
190
191        try {
192            is = new IdentitySubclass("test", iss);
193            is = new IdentitySubclass("test", iss);
194            fail("KeyManagementException was not thrown");
195        } catch (KeyManagementException expected) {
196        }
197    }
198
199    /**
200     * java.security.Identity#getScope()
201     */
202    public void test_getScope() throws Exception {
203        IdentityScope scope = new IdentityScopeSubclass();
204        IdentitySubclass sub = new IdentitySubclass("test", scope);
205        IdentityScope returnedScope = sub.getScope();
206        assertEquals("Wrong Scope returned", scope, returnedScope);
207    }
208
209    /**
210     * java.security.Identity#getPublicKey()
211     */
212    public void test_getPublicKey() throws Exception {
213        IdentitySubclass sub = new IdentitySubclass("test",
214                                                    new IdentityScopeSubclass());
215        sub.setPublicKey(getPubKey());
216        PublicKey returnedPubKey = sub.getPublicKey();
217        assertEquals("Wrong PublicKey returned", getPubKey(), returnedPubKey);
218    }
219
220    /**
221     * java.security.Identity#getName()
222     */
223    public void test_getName() throws Exception {
224        String name = "test";
225        IdentitySubclass sub = new IdentitySubclass(name,
226                                                    new IdentityScopeSubclass());
227        assertEquals("Wrong Name returned", name, sub.getName());
228    }
229
230    /**
231     * java.security.Identity#getInfo()
232     */
233    public void test_getInfo() throws Exception {
234        String info = "This is the general information.";
235        IdentitySubclass sub = new IdentitySubclass("test",
236                                                    new IdentityScopeSubclass());
237        sub.setInfo(info);
238        assertEquals("Wrong Info returned", info, sub.getInfo());
239    }
240
241    /**
242     * java.security.Identity#certificates()
243     */
244    public void test_certificates() throws Exception {
245        IdentitySubclass sub = new IdentitySubclass("test",
246                                                    new IdentityScopeSubclass());
247        CertificateFactory cf = CertificateFactory.getInstance("X.509");
248        X509Certificate cert[] = new X509Certificate[1];
249        cert[0] = (X509Certificate) cf.generateCertificate(certArray);
250        sub.setPublicKey(cert[0].getPublicKey());
251        CertificateImpl certImpl = new CertificateImpl(cert[0]);
252        sub.addCertificate(certImpl);
253        java.security.Certificate[] certs = sub.certificates();
254        assertEquals("Certificate not contained in the identity",
255                     certs[0], certImpl);
256    }
257
258    /**
259     * java.security.Identity#removeCertificate(java.security.Certificate)
260     */
261    // AndroidOnly("Spec says: Removing unknown certificates throw an exception. "
262    //        + "The RI ignores unknown certificates.")
263    public void test_removeCertificateLjava_security_Certificate() throws Exception {
264        IdentitySubclass sub = new IdentitySubclass("test",
265                new IdentityScopeSubclass());
266        CertificateFactory cf = CertificateFactory.getInstance("X.509");
267        X509Certificate cert[] = new X509Certificate[1];
268        cert[0] = (X509Certificate) cf.generateCertificate(certArray);
269        sub.setPublicKey(cert[0].getPublicKey());
270        CertificateImpl certImpl = new CertificateImpl(cert[0]);
271        sub.addCertificate(certImpl);
272
273        try {
274            sub.removeCertificate(null);
275            fail("Test 1: KeyManagementException expected.");
276        } catch (KeyManagementException expected) {
277        }
278        assertEquals("Test 2: Certificate should not have been removed.",
279                1, sub.certificates().length);
280
281        sub.removeCertificate(certImpl);
282        assertEquals("Test 3: Certificate has not been removed.",
283                0, sub.certificates().length);
284
285        // Removing the same certificate a second time should fail.
286        try {
287            sub.removeCertificate(certImpl);
288            fail("Test 4: KeyManagementException expected.");
289        } catch (KeyManagementException expected) {
290        }
291
292    }
293
294    /**
295     * java.security.Identity#equals(java.lang.Object)
296     */
297    public void test_equalsLjava_lang_Object() throws Exception {
298        IdentitySubclass sub = new IdentitySubclass("test",
299                                                    new IdentityScopeSubclass());
300        CertificateFactory cf = CertificateFactory.getInstance("X.509");
301        X509Certificate cert[] = new X509Certificate[1];
302        cert[0] = (X509Certificate) cf.generateCertificate(certArray);
303        sub.setPublicKey(cert[0].getPublicKey());
304        CertificateImpl certImpl = new CertificateImpl(cert[0]);
305        sub.addCertificate(certImpl);
306        IdentitySubclass sub2 = new IdentitySubclass("test",
307                                                     new IdentityScopeSubclass());
308        IdentitySubclass sub3 = new IdentitySubclass("identity name",
309                                                     new IdentityScopeSubclass());
310        assertEquals("the two Identity objects are not equal", sub2, sub);
311        assertEquals(sub, sub2);
312        assertFalse(sub.equals(sub3));
313    }
314
315    /**
316     * java.security.Identity#identityEquals(java.security.Identity)
317     */
318    public void test_identityEqualsLjava_security_Identity() throws Exception {
319        IdentitySubclass sub = new IdentitySubclass("test", null);
320        CertificateFactory cf = CertificateFactory.getInstance("X.509");
321        X509Certificate cert[] = new X509Certificate[1];
322        cert[0] = (X509Certificate) cf.generateCertificate(certArray);
323        sub.setPublicKey(cert[0].getPublicKey());
324        CertificateImpl certImpl = new CertificateImpl(cert[0]);
325        sub.addCertificate(certImpl);
326        IdentitySubclass sub2 = new IdentitySubclass("test", null);
327        sub2.setPublicKey(cert[0].getPublicKey());
328        assertEquals("the two Identity objects are not identity-equal",
329                     sub2, sub);
330    }
331
332    /**
333     * java.security.Identity#toString()
334     */
335    public void test_toString() throws Exception {
336        IdentitySubclass sub = new IdentitySubclass("test", null);
337        assertNotNull(sub.toString());
338        assertTrue("The String returned is not valid", sub.toString().length() > 0);
339        // Regression for HARMONY-1566
340        assertNotNull(new IdentitySubclass().toString());
341    }
342
343    /**
344     * java.security.Identity#toString(boolean)
345     */
346    public void test_toStringZ() throws Exception {
347        IdentitySubclass sub = new IdentitySubclass("test", null);
348        assertNotNull(sub.toString(true));
349        assertTrue("The String returned is not valid", sub.toString(true).length() > 0);
350    }
351
352    /**
353     * java.security.Identity#hashCode()
354     */
355    public void test_hashCode() throws Exception {
356        IdentitySubclass sub = new IdentitySubclass("test", null);
357        IdentitySubclass sub2 = new IdentitySubclass("test", null);
358        assertEquals("The 2 hash codes are not equal", sub.hashCode(), sub2.hashCode());
359    }
360
361    /**
362     * java.security.Identity#setInfo(String)
363     */
364    public void testSetInfo() throws Exception {
365        String[] info = {"This is the general information.", "test", "", null};
366        IdentitySubclass sub = new IdentitySubclass("test", new IdentityScopeSubclass());
367
368        for (int i = 0; i < info.length; i++) {
369            try {
370                sub.setInfo(info[i]);
371                assertEquals("Wrong Info returned", info[i], sub.getInfo());
372            } catch (Exception e) {
373                fail("Unexpected exception for parameter " + info[i]);
374            }
375        }
376
377    }
378
379    /**
380     * java.security.Identity#setPublicKey(PublicKey key)
381     */
382    public void testSetPublicKey() throws Exception{
383        IdentitySubclass sub = new IdentitySubclass("test",
384                                                    new IdentityScopeSubclass());
385        sub.setPublicKey(getPubKey());
386        PublicKey returnedPubKey = sub.getPublicKey();
387        assertEquals("Wrong PublicKey returned", getPubKey(), returnedPubKey);
388
389        sub.setPublicKey(null);
390        assertEquals("Wrong PublicKey returned", null, sub.getPublicKey());
391    }
392
393}
394