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.tests.javax.net.ssl;
19
20import java.io.IOException;
21import java.security.InvalidAlgorithmParameterException;
22import java.security.KeyStore;
23import java.security.KeyStoreException;
24import java.security.NoSuchAlgorithmException;
25import java.security.NoSuchProviderException;
26import java.security.Provider;
27import java.security.Security;
28import java.security.UnrecoverableKeyException;
29import java.security.cert.CertificateException;
30
31import javax.net.ssl.KeyStoreBuilderParameters;
32import javax.net.ssl.ManagerFactoryParameters;
33import javax.net.ssl.KeyManager;
34import javax.net.ssl.KeyManagerFactory;
35import javax.net.ssl.KeyManagerFactorySpi;
36
37import org.apache.harmony.security.tests.support.SpiEngUtils;
38import org.apache.harmony.xnet.tests.support.MyKeyManagerFactorySpi;
39
40import junit.framework.TestCase;
41
42/**
43 * Tests for <code>KeyManagerFactory</code> class constructors and methods.
44 *
45 */
46public class KeyManagerFactory1Test extends TestCase {
47
48    private static final String srvKeyManagerFactory = "KeyManagerFactory";
49
50    private static String defaultAlgorithm = null;
51
52    private static String defaultProviderName = null;
53
54    private static Provider defaultProvider = null;
55
56    private static boolean DEFSupported = false;
57
58    private static final String NotSupportedMsg = "There is no suitable provider for KeyManagerFactory";
59
60    private static final String[] invalidValues = SpiEngUtils.invalidValues;
61
62    private static String[] validValues = new String[3];
63    static {
64        defaultAlgorithm = Security
65                .getProperty("ssl.KeyManagerFactory.algorithm");
66        if (defaultAlgorithm != null) {
67            defaultProvider = SpiEngUtils.isSupport(defaultAlgorithm,
68                    srvKeyManagerFactory);
69            DEFSupported = (defaultProvider != null);
70            defaultProviderName = (DEFSupported ? defaultProvider.getName()
71                    : null);
72            validValues[0] = defaultAlgorithm;
73            validValues[1] = defaultAlgorithm.toUpperCase();
74            validValues[2] = defaultAlgorithm.toLowerCase();
75        }
76    }
77
78    protected KeyManagerFactory[] createKMFac() {
79        if (!DEFSupported) {
80            fail(defaultAlgorithm + " algorithm is not supported");
81            return null;
82        }
83        KeyManagerFactory[] kMF = new KeyManagerFactory[3];
84        try {
85            kMF[0] = KeyManagerFactory.getInstance(defaultAlgorithm);
86            kMF[1] = KeyManagerFactory.getInstance(defaultAlgorithm,
87                    defaultProvider);
88            kMF[2] = KeyManagerFactory.getInstance(defaultAlgorithm,
89                    defaultProviderName);
90            return kMF;
91        } catch (Exception e) {
92            e.printStackTrace();
93            return null;
94        }
95    }
96
97    /**
98     * avax.net.ssl.KeyManagerFactory#getAlgorithm()
99     */
100    public void test_getAlgorithm()
101        throws NoSuchAlgorithmException, NoSuchProviderException {
102        if (!DEFSupported) fail(NotSupportedMsg);
103        assertEquals("Incorrect algorithm",
104                defaultAlgorithm,
105                KeyManagerFactory
106                .getInstance(defaultAlgorithm).getAlgorithm());
107        assertEquals("Incorrect algorithm",
108                defaultAlgorithm,
109                KeyManagerFactory
110                .getInstance(defaultAlgorithm, defaultProviderName)
111                .getAlgorithm());
112        assertEquals("Incorrect algorithm",
113                defaultAlgorithm,
114                KeyManagerFactory.getInstance(defaultAlgorithm, defaultProvider)
115                .getAlgorithm());
116    }
117
118       /**
119     *  Test for <code>getDefaultAlgorithm()</code> method
120     * Assertion: returns value which is specifoed in security property
121     */
122    public void test_getDefaultAlgorithm() {
123        if (!DEFSupported) {
124            fail(NotSupportedMsg);
125            return;
126        }
127        String def = KeyManagerFactory.getDefaultAlgorithm();
128        if (defaultAlgorithm == null) {
129            assertNull("DefaultAlgorithm must be null", def);
130        } else {
131            assertEquals("Invalid default algorithm", def, defaultAlgorithm);
132        }
133        String defA = "Proba.keymanagerfactory.defaul.type";
134        Security.setProperty("ssl.KeyManagerFactory.algorithm", defA);
135        assertEquals("Incorrect defaultAlgorithm",
136                KeyManagerFactory.getDefaultAlgorithm(), defA);
137        if (def == null) {
138            def = "";
139        }
140        Security.setProperty("ssl.KeyManagerFactory.algorithm", def);
141        assertEquals("Incorrect defaultAlgorithm",
142                KeyManagerFactory.getDefaultAlgorithm(), def);
143    }
144
145    /**
146     * Test for <code>getInstance(String algorithm)</code> method
147     * Assertions:
148     * returns security property "ssl.KeyManagerFactory.algorithm";
149     * returns instance of KeyManagerFactory
150     */
151    public void test_getInstanceLjava_lang_String01() throws NoSuchAlgorithmException {
152        if (!DEFSupported) {
153            fail(NotSupportedMsg);
154            return;
155        }
156        KeyManagerFactory keyMF;
157        for (int i = 0; i < validValues.length; i++) {
158            keyMF = KeyManagerFactory.getInstance(validValues[i]);
159            assertNotNull("No KeyManagerFactory created", keyMF);
160            assertEquals("Invalid algorithm", keyMF.getAlgorithm(),
161                    validValues[i]);
162        }
163    }
164
165    /**
166     * Test for <code>getInstance(String algorithm)</code> method
167     * Assertion:
168     * throws NullPointerException when algorithm is null;
169     * throws NoSuchAlgorithmException when algorithm is not correct;
170     */
171    public void test_getInstanceLjava_lang_String02() {
172        try {
173            KeyManagerFactory.getInstance(null);
174            fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null");
175        } catch (NoSuchAlgorithmException e) {
176        } catch (NullPointerException e) {
177        }
178        for (int i = 0; i < invalidValues.length; i++) {
179            try {
180                KeyManagerFactory.getInstance(invalidValues[i]);
181                fail("NoSuchAlgorithmException was not thrown as expected for algorithm: "
182                        .concat(invalidValues[i]));
183            } catch (NoSuchAlgorithmException e) {
184            }
185        }
186    }
187
188    /**
189     * Test for <code>getInstance(String algorithm, String provider)</code>
190     * method
191     * Assertion: throws IllegalArgumentException when provider is null or empty
192     */
193    public void test_getInstanceLjava_lang_StringLjava_lang_String01() throws NoSuchProviderException,
194            NoSuchAlgorithmException {
195        if (!DEFSupported) {
196            fail(NotSupportedMsg);
197            return;
198        }
199        String provider = null;
200        for (int i = 0; i < validValues.length; i++) {
201            try {
202                KeyManagerFactory.getInstance(validValues[i], provider);
203                fail("Expected IllegalArgumentException was not thrown for null provider");
204            } catch (IllegalArgumentException e) {
205            }
206            try {
207                KeyManagerFactory.getInstance(validValues[i], "");
208                fail("Expected IllegalArgumentException was not thrown for empty provider");
209            } catch (IllegalArgumentException e) {
210            }
211        }
212    }
213
214    /**
215     * Test for <code>getInstance(String algorithm, String provider)</code>
216     * method
217     * Assertion:
218     * throws NullPointerException when algorithm is null;
219     * throws NoSuchAlgorithmException when algorithm is not correct;
220     */
221    public void test_getInstanceLjava_lang_StringLjava_lang_String02() throws NoSuchProviderException {
222        if (!DEFSupported) {
223            fail(NotSupportedMsg);
224            return;
225        }
226        try {
227            KeyManagerFactory.getInstance(null, defaultProviderName);
228            fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null");
229        } catch (NoSuchAlgorithmException e) {
230        } catch (NullPointerException e) {
231        }
232        for (int i = 0; i < invalidValues.length; i++) {
233            try {
234                KeyManagerFactory.getInstance(invalidValues[i],
235                        defaultProviderName);
236                fail("NoSuchAlgorithmException must be thrown (algorithm: "
237                        .concat(invalidValues[i]).concat(")"));
238            } catch (NoSuchAlgorithmException e) {
239            }
240        }
241    }
242
243    /**
244     * Test for <code>getInstance(String algorithm, String provider)</code>
245     * method
246     * Assertion: throws NoSuchProviderException when provider has
247     * invalid value
248     */
249    public void test_getInstanceLjava_lang_StringLjava_lang_String03()
250        throws NoSuchAlgorithmException {
251        if (!DEFSupported) {
252            fail(NotSupportedMsg);
253            return;
254        }
255        for (int i = 0; i < validValues.length; i++) {
256            for (int j = 1; j < invalidValues.length; j++) {
257                try {
258                    KeyManagerFactory.getInstance(validValues[i],
259                            invalidValues[j]);
260                    fail("NuSuchProviderException must be thrown (algorithm: "
261                            + validValues[i] + " provider: " + invalidValues[j]
262                            + ")");
263                } catch (NoSuchProviderException e) {
264                }
265            }
266        }
267    }
268
269    /**
270     * Test for <code>getInstance(String algorithm, String provider)</code>
271     * method Assertion: returns instance of KeyManagerFactory
272     */
273    public void test_getInstanceLjava_lang_StringLjava_lang_String04()
274        throws NoSuchProviderException,
275            NoSuchAlgorithmException {
276        if (!DEFSupported) {
277            fail(NotSupportedMsg);
278            return;
279        }
280        KeyManagerFactory kMF;
281        for (int i = 0; i < validValues.length; i++) {
282            kMF = KeyManagerFactory.getInstance(validValues[i],
283                    defaultProviderName);
284            assertNotNull("No KeyManagerFactory created", kMF);
285            assertEquals("Incorrect algorithm", kMF.getAlgorithm(),
286                    validValues[i]);
287            assertEquals("Incorrect provider", kMF.getProvider().getName(),
288                    defaultProviderName);
289        }
290    }
291
292    /**
293     * Test for <code>getInstance(String algorithm, Provider provider)</code>
294     * method
295     * Assertion: throws IllegalArgumentException when provider is null
296     */
297    public void test_getInstanceLjava_lang_StringLjava_security_Provider01()
298        throws NoSuchAlgorithmException {
299        if (!DEFSupported) {
300            fail(NotSupportedMsg);
301            return;
302        }
303        Provider provider = null;
304        for (int i = 0; i < validValues.length; i++) {
305            try {
306                KeyManagerFactory.getInstance(validValues[i], provider);
307                fail("Expected IllegalArgumentException was not thrown when provider is null");
308            } catch (IllegalArgumentException e) {
309            }
310        }
311    }
312
313    /**
314     * Test for <code>getInstance(String algorithm, Provider provider)</code>
315     * method
316     * Assertion:
317     * throws NullPointerException when algorithm is null;
318     * throws NoSuchAlgorithmException when algorithm is not correct;
319     */
320    public void test_getInstanceLjava_lang_StringLjava_security_Provider02() {
321        if (!DEFSupported) {
322            fail(NotSupportedMsg);
323            return;
324        }
325        try {
326            KeyManagerFactory.getInstance(null, defaultProvider);
327            fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null");
328        } catch (NoSuchAlgorithmException e) {
329        } catch (NullPointerException e) {
330        }
331        for (int i = 0; i < invalidValues.length; i++) {
332            try {
333                KeyManagerFactory
334                        .getInstance(invalidValues[i], defaultProvider);
335                fail("Expected NuSuchAlgorithmException was not thrown");
336            } catch (NoSuchAlgorithmException e) {
337            }
338        }
339    }
340
341    /**
342     * Test for <code>getInstance(String algorithm, Provider provider)</code>
343     * method
344     * Assertion: returns instance of KeyManagerFactory
345     */
346    public void test_getInstanceLjava_lang_StringLjava_security_Provider03()
347        throws NoSuchAlgorithmException,
348            IllegalArgumentException {
349        if (!DEFSupported) {
350            fail(NotSupportedMsg);
351            return;
352        }
353        KeyManagerFactory kMF;
354        for (int i = 0; i < validValues.length; i++) {
355            kMF = KeyManagerFactory
356                    .getInstance(validValues[i], defaultProvider);
357            assertNotNull("No KeyManagerFactory created", kMF);
358            assertEquals(kMF.getAlgorithm(), validValues[i]);
359            assertEquals(kMF.getProvider(), defaultProvider);
360        }
361    }
362
363    /**
364     * Test for <code>KeyManagerFactory</code> constructor
365     * Assertion: returns KeyManagerFactory object
366     */
367    public void test_Constructor() throws NoSuchAlgorithmException {
368        if (!DEFSupported) {
369            fail(NotSupportedMsg);
370            return;
371        }
372        KeyManagerFactorySpi spi = new MyKeyManagerFactorySpi();
373        KeyManagerFactory keyMF = new myKeyManagerFactory(spi, defaultProvider,
374                defaultAlgorithm);
375        assertEquals("Incorrect algorithm", keyMF.getAlgorithm(),
376                defaultAlgorithm);
377        assertEquals("Incorrect provider", keyMF.getProvider(), defaultProvider);
378        try {
379            keyMF.init(null, new char[1]);
380            fail("UnrecoverableKeyException must be thrown");
381        } catch (UnrecoverableKeyException e) {
382        } catch (Exception e) {
383            fail("Unexpected: "+e.toString()+" was thrown");
384        }
385        keyMF = new myKeyManagerFactory(null, null, null);
386        assertNull("Aalgorithm must be null", keyMF.getAlgorithm());
387        assertNull("Provider must be null", keyMF.getProvider());
388        try {
389            keyMF.getKeyManagers();
390        } catch (NullPointerException e) {
391        }
392    }
393
394    /**
395     * avax.net.ssl.KeyManagerFactory#getKeyManagers()
396     * @throws NoSuchAlgorithmException
397     * @throws KeyStoreException
398     * @throws IOException
399     * @throws CertificateException
400     * @throws UnrecoverableKeyException
401     */
402    public void test_getKeyManagers()
403        throws Exception {
404        if (!DEFSupported) fail(NotSupportedMsg);
405        KeyManagerFactory kmf = KeyManagerFactory.getInstance(defaultAlgorithm);
406        char[] pass = "password".toCharArray();
407        kmf.init(null, pass);
408        assertNotNull("Key manager array is null", kmf.getKeyManagers());
409        assertEquals("Incorrect size of array",
410                1, kmf.getKeyManagers().length);
411    }
412
413    /**
414     * avax.net.ssl.KeyManagerFactory#getProvider()
415     */
416    public void test_getProvider()
417        throws Exception {
418        if (!DEFSupported) fail(NotSupportedMsg);
419        assertEquals("Incorrect provider",
420                defaultProvider,
421                KeyManagerFactory
422                .getInstance(defaultAlgorithm).getProvider());
423        assertEquals("Incorrect provider",
424                defaultProvider,
425                KeyManagerFactory
426                .getInstance(defaultAlgorithm, defaultProviderName)
427                .getProvider());
428        assertEquals("Incorrect provider",
429                defaultProvider,
430                KeyManagerFactory.getInstance(defaultAlgorithm, defaultProvider)
431                .getProvider());
432    }
433
434    /**
435     * Test for <code>init(KeyStore keyStore, char[] password)</code> and
436     * <code>getKeyManagers()</code>
437     * Assertion: returns not empty KeyManager array
438     */
439    public void test_initLjava_security_KeyStore$C()
440        throws NoSuchAlgorithmException,
441        KeyStoreException, UnrecoverableKeyException {
442        if (!DEFSupported) {
443            fail(NotSupportedMsg);
444            return;
445        }
446        KeyManagerFactory[] keyMF = createKMFac();
447        assertNotNull("KeyManagerFactory object were not created", keyMF);
448        KeyStore ksNull = null;
449        KeyManager[] km;
450        for (int i = 0; i < keyMF.length; i++) {
451            keyMF[i].init(ksNull, new char[10]);
452            km = keyMF[i].getKeyManagers();
453            assertNotNull("Result should not be null", km);
454            assertTrue("Length of result KeyManager array should not be 0",
455                    (km.length > 0));
456        }
457        KeyStore ks;
458        try {
459            ks = KeyStore.getInstance(KeyStore.getDefaultType());
460            ks.load(null, null);
461        } catch (KeyStoreException e) {
462            fail(e.toString() + "default KeyStore type is not supported");
463            return;
464        } catch (Exception e) {
465            fail("Unexpected: " + e.toString());
466            return;
467        }
468        for (int i = 0; i < keyMF.length; i++) {
469            try {
470                keyMF[i].init(ks, new char[10]);
471            } catch (KeyStoreException e) {
472            }
473            km = keyMF[i].getKeyManagers();
474            assertNotNull("Result has not be null", km);
475            assertTrue("Length of result KeyManager array should not be 0",
476                    (km.length > 0));
477        }
478
479    }
480
481    /**
482     * Test for <code>init(ManagerFactoryParameters params)</code>
483     * Assertion:
484     * throws InvalidAlgorithmParameterException when params is null
485     */
486    public void test_initLjavax_net_ssl_ManagerFactoryParameters()
487        throws NoSuchAlgorithmException {
488
489        if (!DEFSupported) {
490            fail(NotSupportedMsg);
491            return;
492        }
493        ManagerFactoryParameters par = null;
494        KeyManagerFactory[] keyMF = createKMFac();
495        assertNotNull("KeyManagerFactory object were not created", keyMF);
496        for (int i = 0; i < keyMF.length; i++) {
497            try {
498                keyMF[i].init(par);
499                fail("InvalidAlgorithmParameterException must be thrown");
500            } catch (InvalidAlgorithmParameterException e) {
501            }
502        }
503
504        KeyStore.ProtectionParameter pp = new ProtectionParameterImpl();
505        KeyStore.Builder bld = KeyStore.Builder.newInstance("testType", null, pp);
506        assertNotNull("Null object KeyStore.Builder", bld);
507
508        try {
509            KeyManagerFactory kmf = KeyManagerFactory.getInstance(defaultAlgorithm);
510            KeyStoreBuilderParameters ksp = new KeyStoreBuilderParameters(bld);
511            assertNotNull(ksp.getParameters());
512            kmf.init(ksp);
513            fail("InvalidAlgorithmParameterException must be thrown");
514        } catch (InvalidAlgorithmParameterException e) {
515        }
516    }
517
518}
519
520/**
521 * Additional class for KeyManagerFactory constructor verification
522 */
523class myKeyManagerFactory extends KeyManagerFactory {
524    public myKeyManagerFactory(KeyManagerFactorySpi spi, Provider prov,
525            String alg) {
526        super(spi, prov, alg);
527    }
528}
529
530class ProtectionParameterImpl implements KeyStore.ProtectionParameter {
531    ProtectionParameterImpl(){}
532}
533