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
18/**
19 * @author Vera Y. Petrashkova
20 */
21
22package org.apache.harmony.security.tests.java.security;
23
24import java.io.ByteArrayOutputStream;
25import java.io.IOException;
26import java.security.KeyStore;
27import java.security.KeyStoreException;
28import java.security.NoSuchAlgorithmException;
29import java.security.NoSuchProviderException;
30import java.security.Provider;
31import java.security.Security;
32import java.security.UnrecoverableEntryException;
33import java.security.UnrecoverableKeyException;
34import java.security.cert.Certificate;
35import java.security.cert.CertificateException;
36import java.util.Date;
37
38import javax.crypto.spec.SecretKeySpec;
39
40import org.apache.harmony.security.tests.support.KeyStoreTestSupport;
41import org.apache.harmony.security.tests.support.MyLoadStoreParams;
42import org.apache.harmony.security.tests.support.SpiEngUtils;
43import org.apache.harmony.security.tests.support.cert.MyCertificate;
44
45import junit.framework.TestCase;
46
47/**
48 * Tests for <code>KeyStore</code> constructor and methods
49 */
50
51public class KeyStore_Impl2Test extends TestCase {
52
53    private static final String KeyStoreProviderClass =
54            "org.apache.harmony.security.tests.support.MyKeyStoreSpi";
55
56    private static final String defaultAlg = "KeyStore";
57
58    private static final String[] invalidValues = SpiEngUtils.invalidValues;
59
60    private static final String[] validValues;
61
62    static {
63        validValues = new String[4];
64        validValues[0] = defaultAlg;
65        validValues[1] = defaultAlg.toLowerCase();
66        validValues[2] = "kEyStOrE";
67        validValues[3] = "KeysTORE";
68    }
69
70    Provider mProv;
71
72    protected void setUp() throws Exception {
73        super.setUp();
74        mProv = (new SpiEngUtils()).new MyProvider("MyKSProvider",
75                "Testing provider", KeyStoreTestSupport.srvKeyStore.concat(".").concat(
76                defaultAlg), KeyStoreProviderClass);
77        Security.insertProviderAt(mProv, 2);
78    }
79
80    /*
81     * @see TestCase#tearDown()
82     */
83    protected void tearDown() throws Exception {
84        super.tearDown();
85        Security.removeProvider(mProv.getName());
86    }
87
88    private void checkResult(KeyStore keyS) throws KeyStoreException,
89            IOException, CertificateException, NoSuchAlgorithmException,
90            UnrecoverableKeyException {
91        char[] pass = { 'a', 'b', 'c' };
92        String alias = "aaa";
93        keyS.load(null, pass);
94        assertNull("getKey must return null", keyS.getKey(alias, pass));
95        assertNull("getCertificate must return null", keyS
96                .getCertificate(alias));
97        assertNull("getCertificateChain must return null", keyS
98                .getCertificateChain(alias));
99        assertEquals("Incorrect result of getCreationDate", keyS
100                .getCreationDate(alias), new Date(0));
101        assertEquals("Incorrect result of size", keyS.size(), 0);
102        assertFalse("Incorrect result of isCertificateEntry", keyS
103                .isCertificateEntry(alias));
104        assertFalse("Incorrect result of isKeyEntry", keyS.isKeyEntry(alias));
105        assertFalse("Incorrect result of containsAlias", keyS
106                .containsAlias(alias));
107        assertEquals("Incorrect result of getCertificateAlias", keyS
108                .getCertificateAlias(null), "");
109        try {
110            keyS.setCertificateEntry(alias, null);
111            fail("KeyStoreException must be thrown because this method is not supported");
112        } catch (KeyStoreException e) {
113        }
114        try {
115            keyS.setEntry(alias, null, null);
116            fail("NullPointerException must be thrown entry is null");
117        } catch (NullPointerException e) {
118        }
119        KeyStore.TrustedCertificateEntry entry = new KeyStore.TrustedCertificateEntry(
120                new MyCertificate("type", new byte[0]));
121        try {
122            keyS.setEntry(alias, entry, null);
123            fail("KeyStoreException must be thrown because this method is not supported");
124        } catch (KeyStoreException e) {
125        }
126        try {
127            keyS.setKeyEntry(alias, new byte[0], null);
128            fail("KeyStoreException must be thrown because this method is not supported");
129        } catch (KeyStoreException e) {
130        }
131        try {
132            keyS.setKeyEntry(alias, null, null);
133            fail("KeyStoreException must be thrown because this method is not supported");
134        } catch (KeyStoreException e) {
135        }
136        try {
137            keyS.store(new ByteArrayOutputStream(), null);
138            fail("IOException must be thrown");
139        } catch (IOException e) {
140        }
141        try {
142            keyS.store(null, new char[0]);
143            fail("IOException or NullPointerException must be thrown for null OutputStream");
144        } catch (IOException e) {
145        } catch (NullPointerException e) {
146        }
147        ByteArrayOutputStream ba = new ByteArrayOutputStream();
148        try {
149            keyS.store(ba, new char[0]);
150            fail("IOException must be thrown");
151        } catch (IOException e) {
152        }
153
154        KeyStore.LoadStoreParameter lParam = new MyLoadStoreParams(
155                new KeyStore.PasswordProtection(new char[0]));
156        try {
157            keyS.store(null);
158            fail("UnsupportedOperationException must be thrown");
159        } catch (UnsupportedOperationException e) {
160        }
161
162
163        //No exception should be thrown out.
164        keyS.load(null);
165
166        try {
167            keyS.store(lParam);
168            fail("UnsupportedOperationException must be thrown");
169        } catch (UnsupportedOperationException e) {
170        }
171
172        keyS.load(lParam);
173
174        //make it compilable on 1.5
175        Class c = alias.getClass();
176        assertFalse("Incorrect result of entryInstanceOf", keyS
177                .entryInstanceOf(alias, c));
178    }
179
180    private void checkKeyStoreException(KeyStore keyS)
181            throws KeyStoreException, UnrecoverableKeyException,
182            UnrecoverableEntryException, NoSuchAlgorithmException, IOException,
183            CertificateException {
184        String alias = "aaa";
185        String eMsg = "IllegalStateException must be thrown because key store was not initialized";
186        try {
187            keyS.aliases();
188            fail(eMsg);
189        } catch (KeyStoreException e) {
190        }
191        try {
192            keyS.containsAlias(alias);
193            fail(eMsg);
194        } catch (KeyStoreException e) {
195        }
196        try {
197            keyS.deleteEntry(alias);
198            fail(eMsg);
199        } catch (KeyStoreException e) {
200        }
201        try {
202            //make it compilable on 1.5
203            Class c = alias.getClass();
204            keyS.entryInstanceOf(alias, c);
205            fail(eMsg);
206        } catch (KeyStoreException e) {
207        }
208        try {
209            keyS.getCertificate(alias);
210            fail(eMsg);
211        } catch (KeyStoreException e) {
212        }
213        MyCertificate mc = new MyCertificate("type", new byte[0]);
214        try {
215            keyS.getCertificateAlias(mc);
216            fail(eMsg);
217        } catch (KeyStoreException e) {
218        }
219        try {
220            keyS.getCertificateChain(alias);
221            fail(eMsg);
222        } catch (KeyStoreException e) {
223        }
224        try {
225            keyS.getCreationDate(alias);
226            fail(eMsg);
227        } catch (KeyStoreException e) {
228        }
229        KeyStore.PasswordProtection pp = new KeyStore.PasswordProtection(
230                new char[0]);
231        try {
232            keyS.getEntry(alias, pp);
233            fail(eMsg);
234        } catch (KeyStoreException e) {
235        }
236        try {
237            keyS.getKey(alias, new char[0]);
238            fail(eMsg);
239        } catch (KeyStoreException e) {
240        }
241        try {
242            keyS.isCertificateEntry(alias);
243            fail(eMsg);
244        } catch (KeyStoreException e) {
245        }
246        try {
247            keyS.isKeyEntry(alias);
248            fail(eMsg);
249        } catch (KeyStoreException e) {
250        }
251        KeyStore.TrustedCertificateEntry entry = new KeyStore.TrustedCertificateEntry(
252                mc);
253        Certificate[] chain = { mc };
254        try {
255            keyS.setEntry(alias, entry, pp);
256            fail(eMsg);
257        } catch (KeyStoreException e) {
258        }
259        try {
260            keyS.setKeyEntry(alias, new byte[0], chain);
261            fail(eMsg);
262        } catch (KeyStoreException e) {
263        }
264        SecretKeySpec sks = new SecretKeySpec(new byte[10], "type");
265        try {
266            keyS.setKeyEntry(alias, sks, new char[0], chain);
267            fail(eMsg);
268        } catch (KeyStoreException e) {
269        }
270        try {
271            keyS.size();
272            fail(eMsg);
273        } catch (KeyStoreException e) {
274        }
275        ByteArrayOutputStream ba = new ByteArrayOutputStream();
276        try {
277            keyS.store(ba, new char[0]);
278            fail(eMsg);
279        } catch (KeyStoreException e) {
280        }
281        KeyStore.LoadStoreParameter lParam = new MyLoadStoreParams(
282                new KeyStore.PasswordProtection(new char[0]));
283        try {
284            keyS.store(lParam);
285            fail(eMsg);
286        } catch (KeyStoreException e) {
287        }
288    }
289
290
291    /**
292     * Test for <code>getInstance(String type)</code> method
293     * Assertions:
294     * throws NullPointerException when type is null
295     * throws KeyStoreException when type is  not available;
296     * returns KeyStore object
297     */
298    public void testGetInstance01() throws KeyStoreException,
299            UnrecoverableKeyException, UnrecoverableEntryException,
300            NoSuchAlgorithmException, IOException, CertificateException {
301        try {
302            KeyStore.getInstance(null);
303            fail("NullPointerException or KeyStoreException must be thrown");
304        } catch (KeyStoreException e) {
305        } catch (NullPointerException e) {
306        }
307        for (int i = 0; i < invalidValues.length; i++) {
308            try {
309                KeyStore.getInstance(invalidValues[i]);
310                fail("KeyStoreException must be thrown (type: ".concat(
311                        invalidValues[i]).concat(")"));
312            } catch (KeyStoreException e) {
313            }
314        }
315        KeyStore keyS;
316        for (int i = 0; i < validValues.length; i++) {
317            keyS = KeyStore.getInstance(validValues[i]);
318            assertEquals("Incorrect type", keyS.getType(), validValues[i]);
319            assertEquals("Incorrect provider", keyS.getProvider(), mProv);
320            checkKeyStoreException(keyS);
321            checkResult(keyS);
322        }
323    }
324
325    /**
326     * Test for <code>getInstance(String type, String provider)</code> method
327     * Assertions:
328     * throws NullPointerException when type is null
329     * throws KeyStoreException when type is  not available;
330     * throws IllegalArgumentException when provider is null;
331     * throws NoSuchProviderException when provider is available;
332     * returns KeyStore object
333     */
334    public void testGetInstance02() throws KeyStoreException,
335            NoSuchProviderException, IllegalArgumentException,
336            UnrecoverableKeyException, UnrecoverableEntryException,
337            NoSuchAlgorithmException, IOException, CertificateException {
338        try {
339            KeyStore.getInstance(null, mProv.getName());
340            fail("NullPointerException or KeyStoreException must be thrown");
341        } catch (KeyStoreException e) {
342        } catch (NullPointerException e) {
343        }
344        for (int i = 0; i < invalidValues.length; i++) {
345            try {
346                KeyStore.getInstance(invalidValues[i], mProv.getName());
347                fail("KeyStoreException must be thrown (type: ".concat(
348                        invalidValues[i]).concat(")"));
349            } catch (KeyStoreException e) {
350            }
351        }
352        String prov = null;
353        for (int i = 0; i < validValues.length; i++) {
354            try {
355                KeyStore.getInstance(validValues[i], prov);
356                fail("IllegalArgumentException must be thrown when provider is null (type: "
357                        .concat(invalidValues[i]).concat(")"));
358            } catch (IllegalArgumentException e) {
359            }
360        }
361        for (int i = 0; i < validValues.length; i++) {
362            for (int j = 1; j < invalidValues.length; j++) {
363                try {
364                    KeyStore.getInstance(validValues[i], invalidValues[j]);
365                    fail("NoSuchProviderException must be thrown (type: "
366                            .concat(invalidValues[i]).concat(" provider: ")
367                            .concat(invalidValues[j]).concat(")"));
368                } catch (NoSuchProviderException e) {
369                }
370            }
371        }
372        KeyStore keyS;
373        for (int i = 0; i < validValues.length; i++) {
374            keyS = KeyStore.getInstance(validValues[i], mProv.getName());
375            assertEquals("Incorrect type", keyS.getType(), validValues[i]);
376            assertEquals("Incorrect provider", keyS.getProvider().getName(),
377                    mProv.getName());
378            checkKeyStoreException(keyS);
379            checkResult(keyS);
380        }
381    }
382
383    /**
384     * Test for <code>getInstance(String type, Provider provider)</code>
385     * method
386     * Assertions:
387     * throws NullPointerException when type is null
388     * } catch (KeyStoreException e) {
389     * throws IllegalArgumentException when provider is null;
390     * returns KeyStore object
391     */
392    public void testGetInstance03() throws KeyStoreException,
393            IllegalArgumentException, UnrecoverableKeyException,
394            UnrecoverableEntryException, NoSuchAlgorithmException, IOException,
395            CertificateException {
396        try {
397            KeyStore.getInstance(null, mProv);
398            fail("KeyStoreException must be thrown");
399        } catch (KeyStoreException e) {
400        } catch (NullPointerException e) {
401        }
402        for (int i = 0; i < invalidValues.length; i++) {
403            try {
404                KeyStore.getInstance(invalidValues[i], mProv);
405                fail("KeyStoreException must be thrown (type: ".concat(
406                        invalidValues[i]).concat(")"));
407            } catch (KeyStoreException e) {
408            }
409        }
410        Provider prov = null;
411        for (int i = 0; i < validValues.length; i++) {
412            try {
413                KeyStore.getInstance(validValues[i], prov);
414                fail("IllegalArgumentException must be thrown when provider is null (type: "
415                        .concat(invalidValues[i]).concat(")"));
416            } catch (IllegalArgumentException e) {
417            }
418        }
419        KeyStore keyS;
420        for (int i = 0; i < validValues.length; i++) {
421            keyS = KeyStore.getInstance(validValues[i], mProv);
422            assertEquals("Incorrect type", keyS.getType(), validValues[i]);
423            assertEquals("Incorrect provider", keyS.getProvider(), mProv);
424            checkKeyStoreException(keyS);
425            checkResult(keyS);
426        }
427    }
428
429}
430