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* @version $Revision$
21*/
22
23package org.apache.harmony.security.tests.java.security;
24
25import java.math.BigInteger;
26import java.security.InvalidAlgorithmParameterException;
27import java.security.InvalidParameterException;
28import java.security.KeyPair;
29import java.security.KeyPairGenerator;
30import java.security.NoSuchAlgorithmException;
31import java.security.NoSuchProviderException;
32import java.security.Provider;
33import java.security.SecureRandom;
34import java.security.spec.AlgorithmParameterSpec;
35
36import org.apache.harmony.security.tests.support.MyKeyPairGenerator1;
37import org.apache.harmony.security.tests.support.MyKeyPairGenerator2;
38import org.apache.harmony.security.tests.support.SpiEngUtils;
39
40import junit.framework.TestCase;
41
42/**
43 * Tests for <code>KeyPairGenerator</code> class constructors and methods.
44 *
45 */
46public class KeyPairGenerator1Test extends TestCase {
47
48    private static String[] invalidValues = SpiEngUtils.invalidValues;
49
50    public static final String srvKeyPairGenerator = "KeyPairGenerator";
51
52    public static String[] algs = {
53            "DSA", "dsa", "Dsa", "DsA", "dsA" };
54
55    public static String validAlgName = "DSA";
56
57    private static String validProviderName = null;
58
59    public static Provider validProvider = null;
60
61    private static boolean DSASupported = false;
62
63    public static String NotSupportMsg = "";
64
65    static {
66        validProvider = SpiEngUtils.isSupport(
67                validAlgName,
68                srvKeyPairGenerator);
69        DSASupported = (validProvider != null);
70        if (!DSASupported) {
71            NotSupportMsg = validAlgName + " algorithm is not supported" ;
72        }
73        validProviderName = (DSASupported ? validProvider.getName() : null);
74    }
75
76    protected KeyPairGenerator [] createKPGen() {
77        if (!DSASupported) {
78            fail(NotSupportMsg);
79            return null;
80        }
81        KeyPairGenerator[] kpg = new KeyPairGenerator[3];
82        try {
83            kpg[0] = KeyPairGenerator.getInstance(validAlgName);
84            kpg[1] = KeyPairGenerator.getInstance(validAlgName, validProvider);
85            kpg[2] = KeyPairGenerator.getInstance(validAlgName, validProviderName);
86            return kpg;
87        } catch (Exception e) {
88            e.printStackTrace();
89            return null;
90        }
91    }
92
93    /**
94     * Test for <code>getInstance(String algorithm)</code> method
95     * Assertion:
96     * throws NullPointerException  when algorithm is null
97     * throws NoSuchAlgorithmException when algorithm is incorrect;
98     */
99    public void testKeyPairGenerator01() throws NoSuchAlgorithmException {
100        try {
101            KeyPairGenerator.getInstance(null);
102            fail("NullPointerException or NoSuchAlgorithmException must be thrown  when algorithm is null");
103        } catch (NoSuchAlgorithmException e) {
104        } catch (NullPointerException e) {
105        }
106        for (int i = 0; i < invalidValues.length; i++) {
107            try {
108                KeyPairGenerator.getInstance(invalidValues[i]);
109                fail("NoSuchAlgorithmException must be thrown when algorithm is not available: "
110                        .concat(invalidValues[i]));
111            } catch (NoSuchAlgorithmException e) {
112            }
113        }
114    }
115
116    /**
117     * Test for <code>getInstance(String algorithm)</code> method
118     * Assertion: returns KeyPairGenerator object
119     */
120    public void testKeyPairGenerator02() throws NoSuchAlgorithmException {
121        if (!DSASupported) {
122            fail(NotSupportMsg);
123            return;
124        }
125        KeyPairGenerator kpg;
126        for (int i = 0; i < algs.length; i++) {
127            kpg = KeyPairGenerator.getInstance(algs[i]);
128            assertEquals("Incorrect algorithm ", kpg.getAlgorithm().toUpperCase(),
129                    algs[i].toUpperCase());
130        }
131    }
132
133    /**
134     * Test for <code>getInstance(String algorithm, String provider)</code>
135     * method
136     * Assertion: throws IllegalArgumentException when provider is null or empty
137     */
138    public void testKeyPairGenerator03() throws NoSuchAlgorithmException,
139            NoSuchProviderException {
140        if (!DSASupported) {
141            fail(NotSupportMsg);
142            return;
143        }
144        String provider = null;
145        for (int i = 0; i < algs.length; i++) {
146            try {
147                KeyPairGenerator.getInstance(algs[i], provider);
148                fail("IllegalArgumentException must be thrown when provider is null");
149            } catch (IllegalArgumentException e) {
150            }
151            try {
152                KeyPairGenerator.getInstance(algs[i], "");
153                fail("IllegalArgumentException must be thrown when provider is empty");
154            } catch (IllegalArgumentException e) {
155            }
156        }
157    }
158
159    /**
160     * Test for <code>getInstance(String algorithm, String provider)</code>
161     * method
162     * Assertion:
163     * throws NoSuchProviderException when provider is not available
164     */
165    public void testKeyPairGenerator04() throws NoSuchAlgorithmException,
166            IllegalArgumentException {
167        if (!DSASupported) {
168            fail(NotSupportMsg);
169            return;
170        }
171        for (int i = 0; i < algs.length; i++) {
172            for (int j = 1; j < invalidValues.length; j++) {
173                try {
174                    KeyPairGenerator.getInstance(algs[i], invalidValues[j]);
175                    fail("NoSuchProviderException must be thrown (algorithm: "
176                            .concat(algs[i]).concat(" provider: ").concat(
177                                    invalidValues[j]).concat(")"));
178                } catch (NoSuchProviderException e) {
179                }
180            }
181        }
182    }
183
184    /**
185     * Test for <code>getInstance(String algorithm, String provider)</code>
186     * method
187     * Assertion: throws NoSuchAlgorithmException when algorithm is not
188     * available
189     * throws NullPointerException  when algorithm is null
190     * throws NoSuchAlgorithmException when algorithm is incorrect;
191     */
192    public void testKeyPairGenerator05() throws NoSuchProviderException,
193            IllegalArgumentException {
194        if (!DSASupported) {
195            fail(NotSupportMsg);
196            return;
197        }
198        try {
199            KeyPairGenerator.getInstance(null, validProviderName);
200            fail("NullPointerException or NoSuchAlgorithmException must be thrown  when algorithm is null");
201        } catch (NoSuchAlgorithmException e) {
202        } catch (NullPointerException e) {
203        }
204        for (int i = 0; i < invalidValues.length; i++) {
205            try {
206                KeyPairGenerator.getInstance(invalidValues[i],
207                        validProviderName);
208                fail("NoSuchAlgorithmException must be thrown (algorithm: "
209                        .concat(algs[i]).concat(" provider: ").concat(
210                                validProviderName).concat(")"));
211            } catch (NoSuchAlgorithmException e) {
212            }
213        }
214    }
215
216    /**
217     * Test for <code>getInstance(String algorithm, String provider)</code>
218     * method
219     * Assertion: returns KeyPairGenerator object
220     */
221    public void testKeyPairGenerator06() throws NoSuchProviderException,
222            NoSuchAlgorithmException, IllegalArgumentException {
223        if (!DSASupported) {
224            fail(NotSupportMsg);
225            return;
226        }
227        KeyPairGenerator kpg;
228        for (int i = 0; i < algs.length; i++) {
229            kpg = KeyPairGenerator.getInstance(algs[i], validProviderName);
230            assertEquals("Incorrect algorithm", kpg.getAlgorithm().toUpperCase(),
231                    algs[i].toUpperCase());
232            assertEquals("Incorrect provider", kpg.getProvider().getName(),
233                    validProviderName);
234        }
235    }
236
237    /**
238     * Test for <code>getInstance(String algorithm, Provider provider)</code>
239     * method
240     * Assertion: throws IllegalArgumentException when provider is null
241     */
242    public void testKeyPairGenerator07() throws NoSuchAlgorithmException {
243        if (!DSASupported) {
244            fail(NotSupportMsg);
245            return;
246        }
247        Provider provider = null;
248        for (int i = 0; i < algs.length; i++) {
249            try {
250                KeyPairGenerator.getInstance(algs[i], provider);
251                fail("IllegalArgumentException must be thrown when provider is null");
252            } catch (IllegalArgumentException e) {
253            }
254        }
255    }
256
257    /**
258     * Test for <code>getInstance(String algorithm, Provider provider)</code>
259     * method
260     * Assertion:
261     * throws NullPointerException  when algorithm is null
262     * throws NoSuchAlgorithmException when algorithm is incorrect;
263     */
264    public void testKeyPairGenerator08() throws IllegalArgumentException {
265        if (!DSASupported) {
266            fail(NotSupportMsg);
267            return;
268        }
269        try {
270            KeyPairGenerator.getInstance(null, validProvider);
271            fail("NullPointerException or NoSuchAlgorithmException must be thrown  when algorithm is null");
272        } catch (NoSuchAlgorithmException e) {
273        } catch (NullPointerException e) {
274        }
275        for (int i = 0; i < invalidValues.length; i++) {
276            try {
277                KeyPairGenerator.getInstance(invalidValues[i], validProvider);
278                fail("NoSuchAlgorithmException must be thrown (algorithm: "
279                        .concat(algs[i]).concat(" provider: ").concat(
280                                validProviderName).concat(")"));
281            } catch (NoSuchAlgorithmException e) {
282            }
283        }
284    }
285
286    /**
287     * Test for <code>getInstance(String algorithm, Provider provider)</code>
288     * method
289     * Assertion: returns KeyPairGenerator object
290     */
291    public void testKeyPairGenerator09() throws NoSuchAlgorithmException,
292            IllegalArgumentException {
293        if (!DSASupported) {
294            fail(NotSupportMsg);
295            return;
296        }
297        KeyPairGenerator kpg;
298        for (int i = 0; i < algs.length; i++) {
299            kpg = KeyPairGenerator.getInstance(algs[i], validProvider);
300            assertEquals("Incorrect algorithm", kpg.getAlgorithm().toUpperCase(),
301                    algs[i].toUpperCase());
302            assertEquals("Incorrect provider", kpg.getProvider(), validProvider);
303        }
304    }
305
306    /**
307     * Test for <code>generateKeyPair()</code> and <code>genKeyPair()</code>
308     * methods
309     * Assertion: KeyPairGenerator was initialized before the invocation
310     * of these methods
311     */
312    public void testKeyPairGenerator10() throws NoSuchAlgorithmException,
313            NoSuchProviderException, IllegalArgumentException {
314            if (!DSASupported) {
315                fail(NotSupportMsg);
316                return;
317            }
318            KeyPairGenerator[] kpg = createKPGen();
319            assertNotNull("KeyPairGenerator objects were not created", kpg);
320            KeyPair kp, kp1;
321            for (int i = 0; i < kpg.length; i++) {
322                kpg[i].initialize(512);
323                kp = kpg[i].generateKeyPair();
324                kp1 = kpg[i].genKeyPair();
325
326                assertFalse("Incorrect private key", kp.getPrivate().equals(
327                        kp1.getPrivate()));
328                assertFalse("Incorrect public key", kp.getPublic().equals(
329                        kp1.getPublic()));
330            }
331    }
332
333    /**
334     * Test for methods:
335     * <code>initialize(int keysize)</code>
336     * <code>initialize(int keysize, SecureRandom random)</code>
337     * <code>initialize(AlgorithmParameterSpec param)</code>
338     * <code>initialize(AlgorithmParameterSpec param, SecureRandom random)</code>
339     * Assertion: throws InvalidParameterException or
340     * InvalidAlgorithmParameterException when parameters keysize or param are
341     * incorrect
342     */
343    public void testKeyPairGenerator11() throws NoSuchAlgorithmException,
344            NoSuchProviderException {
345        if (!DSASupported) {
346            fail(NotSupportMsg);
347            return;
348        }
349        int[] keys =  { -10000, -1024, -1, 0, 10000 };
350        KeyPairGenerator[] kpg = createKPGen();
351        assertNotNull("KeyPairGenerator objects were not created", kpg);
352        SecureRandom random = new SecureRandom();
353        AlgorithmParameterSpec aps = null;
354
355        for (int i = 0; i < kpg.length; i++) {
356
357            for (int j = 0; j < keys.length; j++) {
358                try {
359                    kpg[i].initialize(keys[j]);
360                    kpg[i].initialize(keys[j], random);
361                } catch (InvalidParameterException e) {
362                }
363            }
364
365            try {
366                kpg[i].initialize(aps);
367                kpg[i].initialize(aps, random);
368            } catch (InvalidAlgorithmParameterException e) {
369            }
370        }
371    }
372
373    /**
374     * Test for methods: <code>initialize(int keysize)</code>
375     * <code>initialize(int keysize, SecureRandom random)</code>
376     * <code>initialize(AlgorithmParameterSpec param)</code>
377     * <code>initialize(AlgorithmParameterSpec param, SecureRandom random)</code>
378     * <code>generateKeyPair()</code>
379     * <code>genKeyPair()</code>
380     * Assertion: throws InvalidParameterException or
381     * InvalidAlgorithmParameterException when parameters keysize or param are
382     * incorrect Assertion: generateKeyPair() and genKeyPair() return null
383     * KeyPair Additional class MyKeyPairGenerator1 is used
384     */
385    public void testKeyPairGenerator12() {
386        int[] keys = { -1, -250, 1, 64, 512, 1024 };
387        SecureRandom random = new SecureRandom();
388        AlgorithmParameterSpec aps;
389        KeyPairGenerator mKPG = new MyKeyPairGenerator1("");
390        assertEquals("Incorrect algorithm", mKPG.getAlgorithm(),
391                MyKeyPairGenerator1.getResAlgorithm());
392
393        mKPG.generateKeyPair();
394        mKPG.genKeyPair();
395
396        for (int i = 0; i < keys.length; i++) {
397            try {
398                mKPG.initialize(keys[i]);
399                fail("InvalidParameterException must be thrown (key: "
400                        + Integer.toString(keys[i]) + ")");
401            } catch (InvalidParameterException e) {
402            }
403            try {
404                mKPG.initialize(keys[i], random);
405                fail("InvalidParameterException must be thrown (key: "
406                        + Integer.toString(keys[i]) + ")");
407            } catch (InvalidParameterException e) {
408            }
409        }
410        try {
411            mKPG.initialize(100, null);
412            fail("InvalidParameterException must be thrown when random is null");
413        } catch (InvalidParameterException e) {
414        }
415
416        mKPG.initialize(100, random);
417        assertEquals("Incorrect random", random,
418                ((MyKeyPairGenerator1) mKPG).secureRandom);
419        assertEquals("Incorrect keysize", 100,
420                ((MyKeyPairGenerator1) mKPG).keySize);
421        try {
422            mKPG.initialize(null, random);
423            fail("InvalidAlgorithmParameterException must be thrown when param is null");
424        } catch (InvalidAlgorithmParameterException e) {
425        }
426        if (DSASupported) {
427            BigInteger bInt = new BigInteger("1");
428            aps = new java.security.spec.DSAParameterSpec(bInt, bInt, bInt);
429            try {
430                mKPG.initialize(aps, null);
431                fail("InvalidParameterException must be thrown when random is null");
432            } catch (InvalidParameterException e) {
433            } catch (InvalidAlgorithmParameterException e) {
434                fail("Unexpected InvalidAlgorithmParameterException was thrown");
435            }
436            try {
437                mKPG.initialize(aps, random);
438                assertEquals("Incorrect random", random,
439                        ((MyKeyPairGenerator1) mKPG).secureRandom);
440                assertEquals("Incorrect params", aps,
441                        ((MyKeyPairGenerator1) mKPG).paramSpec);
442            } catch (InvalidAlgorithmParameterException e) {
443                fail("Unexpected InvalidAlgorithmParameterException was thrown");
444            }
445        }
446    }
447
448    /**
449     * Test for methods: <code>initialize(int keysize)</code>
450     * <code>initialize(int keysize, SecureRandom random)</code>
451     * <code>initialize(AlgorithmParameterSpec param)</code>
452     * <code>initialize(AlgorithmParameterSpec param, SecureRandom random)</code>
453     * <code>generateKeyPair()</code>
454     * <code>genKeyPair()</code>
455     * Assertion: initialize(int ...) throws InvalidParameterException when
456     * keysize in incorrect Assertion: initialize(AlgorithmParameterSpec
457     * ...)throws UnsupportedOperationException Assertion: generateKeyPair() and
458     * genKeyPair() return not null KeyPair Additional class MyKeyPairGenerator2
459     * is used
460     */
461    public void testKeyPairGenerator13() {
462        int[] keys = { -1, -250, 1, 63, -512, -1024 };
463        SecureRandom random = new SecureRandom();
464        KeyPairGenerator mKPG = new MyKeyPairGenerator2(null);
465        assertEquals("Algorithm must be null", mKPG.getAlgorithm(),
466                MyKeyPairGenerator2.getResAlgorithm());
467        assertNull("genKeyPair() must return null", mKPG.genKeyPair());
468        assertNull("generateKeyPair() mut return null", mKPG.generateKeyPair());
469        for (int i = 0; i < keys.length; i++) {
470            try {
471                mKPG.initialize(keys[i]);
472                fail("InvalidParameterException must be thrown (key: "
473                        + Integer.toString(keys[i]) + ")");
474            } catch (InvalidParameterException e) {
475            }
476            try {
477                mKPG.initialize(keys[i], random);
478                fail("InvalidParameterException must be thrown (key: "
479                        + Integer.toString(keys[i]) + ")");
480            } catch (InvalidParameterException e) {
481            }
482        }
483        try {
484            mKPG.initialize(64);
485        } catch (InvalidParameterException e) {
486            fail("Unexpected InvalidParameterException was thrown");
487        }
488        try {
489            mKPG.initialize(64, null);
490        } catch (InvalidParameterException e) {
491            fail("Unexpected InvalidParameterException was thrown");
492        }
493        try {
494            mKPG.initialize(null, random);
495        } catch (UnsupportedOperationException e) {
496            // on j2se1.4 this exception is not thrown
497        } catch (InvalidAlgorithmParameterException e) {
498            fail("Unexpected InvalidAlgorithmParameterException was thrown");
499        }
500    }
501}
502