KeyStoreTest.java revision 561ee011997c6c2f1befbfaa9d5f0a99771c1d63
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.IOException;
25import java.security.KeyStore;
26import java.security.KeyStoreException;
27import java.security.Provider;
28import java.security.Security;
29import java.security.SignatureException;
30import java.security.Principal;
31import java.security.PublicKey;
32import java.security.InvalidKeyException;
33import java.security.NoSuchProviderException;
34import java.security.NoSuchAlgorithmException;
35import java.security.cert.Certificate;
36import java.security.cert.CertificateException;
37import java.security.cert.CertificateEncodingException;
38import java.security.cert.CertificateExpiredException;
39import java.security.cert.CertificateNotYetValidException;
40import java.security.cert.X509Certificate;
41import java.util.Date;
42import java.util.Set;
43import java.math.BigInteger;
44
45import javax.crypto.KeyGenerator;
46import javax.crypto.SecretKey;
47
48import org.apache.harmony.security.tests.support.KeyStoreTestSupport;
49import org.apache.harmony.security.tests.support.MyLoadStoreParams;
50import org.apache.harmony.security.tests.support.SpiEngUtils;
51
52import junit.framework.TestCase;
53
54/**
55 * Tests for <code>KeyStore</code> constructor and methods
56 *
57 */
58
59public class KeyStoreTest extends TestCase {
60
61    private static final String KeyStoreProviderClass = "org.apache.harmony.security.tests.support.MyKeyStore";
62
63    private static final String defaultType = "KeyStore";
64
65    public static boolean KSSupported = false;
66
67    public static String defaultProviderName = null;
68
69    public static Provider defaultProvider = null;
70
71    private static String NotSupportMsg = "Default KeyStore type is not supported";
72
73    Provider mProv;
74
75    public KeyStore[] createKS() throws Exception {
76        assertTrue(NotSupportMsg, KSSupported);
77        KeyStore[] kpg = new KeyStore[3];
78
79        kpg[0] = KeyStore.getInstance(defaultType);
80        kpg[1] = KeyStore.getInstance(defaultType, defaultProvider);
81        kpg[2] = KeyStore.getInstance(defaultType, defaultProviderName);
82        return kpg;
83    }
84
85    protected void setUp() throws Exception {
86        super.setUp();
87        mProv = (new SpiEngUtils()).new MyProvider("MyKSProvider",
88                "Testing provider", KeyStoreTestSupport.srvKeyStore.concat(".")
89                        .concat(defaultType), KeyStoreProviderClass);
90        Security.insertProviderAt(mProv, 2);
91        defaultProvider = SpiEngUtils.isSupport(defaultType,
92                KeyStoreTestSupport.srvKeyStore);
93        KSSupported = (defaultProvider != null);
94        defaultProviderName = (KSSupported ? defaultProvider.getName() : null);
95    }
96
97    /*
98     * @see TestCase#tearDown()
99     */
100    protected void tearDown() throws Exception {
101        super.tearDown();
102        Security.removeProvider(mProv.getName());
103    }
104
105    /**
106     * Test for <code>load(LoadStoreParameter param)</code>
107     * <code>store(LoadStoreParameter param)</code>
108     * methods
109     * Assertions: throw IllegalArgumentException if param is null;
110     */
111    public void testLoadStore02() throws Exception {
112        assertTrue(NotSupportMsg, KSSupported);
113
114        KeyStore[] kss = createKS();
115        assertNotNull("KeyStore objects were not created", kss);
116
117        for (int i = 0; i < kss.length; i++) {
118            try {
119                kss[i].load(null);
120                fail("IOException or IllegalArgumentException should be thrown for null parameter");
121            } catch (IOException e) {
122            } catch (IllegalArgumentException e) {
123            }
124            kss[i].load(null, null);
125            try {
126                kss[i].store(null);
127                fail("IOException or IllegalArgumentException should be thrown for null parameter");
128            } catch (IOException e) {
129            } catch (IllegalArgumentException e) {
130            }
131        }
132        KeyStore.LoadStoreParameter lParam = new MyLoadStoreParams(
133                new KeyStore.PasswordProtection(new char[0]));
134        for (int i = 0; i < kss.length; i++) {
135            kss[i].load(lParam);
136            assertEquals("Incorrect result", kss[i].size(), 0);
137            kss[i].store(lParam);
138        }
139    }
140
141
142    /**
143     * Test for <code>setKeyEntry(String alias, byte[] key, Certificate[] chain)</code>
144     * method
145     * Assertion: stores KeyEntry.
146     */
147    public void testSetKeyEntry() throws Exception {
148        assertTrue(NotSupportMsg, KSSupported);
149
150        KeyStore[] kss = createKS();
151        assertNotNull("KeyStore objects were not created", kss);
152        byte[] kk = { (byte) 1, (byte) 2, (byte) 127, (byte) 77 };
153        String alias = "keyEntry";
154        char[] pwd = new char[0];
155        byte[] res;
156        Certificate certs[] = {
157                new KeyStoreTestSupport.MCertificate(alias, kk),
158                new KeyStoreTestSupport.MCertificate(alias, kk) };
159        for (int i = 0; i < kss.length; i++) {
160            kss[i].load(null, null);
161            try {
162                kss[i].setKeyEntry("proba", null, null);
163                fail("KeyStoreException must be thrown");
164            } catch (KeyStoreException e) {
165            }
166            kss[i].setKeyEntry(alias, kk, certs);
167            res = kss[i].getKey(alias, pwd).getEncoded();
168            assertEquals(kk.length, res.length);
169            for (int j = 0; j < res.length; j++) {
170                assertEquals(res[j], kk[j]);
171            }
172            assertEquals(kss[i].getCertificateChain(alias).length, certs.length);
173            kss[i].setKeyEntry(alias, kk, null);
174            res = kss[i].getKey(alias, pwd).getEncoded();
175            assertEquals(kk.length, res.length);
176            for (int j = 0; j < res.length; j++) {
177                assertEquals(res[j], kk[j]);
178            }
179            assertNull(kss[i].getCertificateChain(alias));
180        }
181    }
182
183    /**
184     * Test for <code>getDefaultType()</code> method Assertion: returns
185     * default security key store type or "jks" string
186     */
187    public void testKeyStore01() {
188        String propName = "keystore.type";
189        String defKSType = Security.getProperty(propName);
190        String dType = KeyStore.getDefaultType();
191        String resType = defKSType;
192        if (resType == null) {
193            resType = defaultType;
194        }
195        assertNotNull("Default type have not be null", dType);
196        assertEquals("Incorrect default type", dType, resType);
197
198        if (defKSType == null) {
199            Security.setProperty(propName, defaultType);
200            dType = KeyStore.getDefaultType();
201            resType = Security.getProperty(propName);
202            assertNotNull("Incorrect default type", resType);
203            assertNotNull("Default type have not be null", dType);
204            assertEquals("Incorrect default type", dType, resType);
205        }
206    }
207
208    /**
209     * Test for <code>getInstance(String type)</code> method
210     * Assertion:
211     * throws NullPointerException when type is null
212     * throws KeyStoreException when type is not available
213     *
214     */
215    public void testKeyStore02() throws KeyStoreException {
216        String[] invalidValues =  SpiEngUtils.invalidValues;
217        try {
218            KeyStore.getInstance(null);
219            fail("NullPointerException must be thrown when type is null");
220        } catch (NullPointerException e) {
221        }
222        for (int i = 0; i < invalidValues.length; i++) {
223            try {
224                KeyStore.getInstance(invalidValues[i]);
225                fail("KeyStoreException must be thrown (type: ".concat(
226                        invalidValues[i]).concat(" )"));
227            } catch (KeyStoreException e) {
228            }
229        }
230    }
231
232    /**
233     * @test java.security.KeyStore.PasswordProtection.getPassword()
234     */
235    public void testKeyStorePPGetPassword() {
236        // Regression for HARMONY-1539
237        // no exception expected
238        assertNull(new KeyStore.PasswordProtection(null).getPassword());
239        char[] password = new char[] {'a', 'b', 'c'};
240        KeyStore.PasswordProtection pp = new KeyStore.PasswordProtection(password);
241        assertNotSame(pp.getPassword(), password);
242        assertSame(pp.getPassword(), pp.getPassword());
243
244    }
245
246
247    /*
248     * @tests java.security.KeyStoreSpi.engineEntryInstanceOf(String, Class<? extends Entry>)
249     */
250    public void testEngineEntryInstanceOf() throws Exception {
251        //Regression for HARMONY-615
252
253        // create a KeyStore
254        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
255        keyStore.load(null, "pwd".toCharArray());
256
257        // generate a key
258        KeyGenerator keyGen = KeyGenerator.getInstance("DES");
259        keyGen.init(56);
260        SecretKey secretKey = keyGen.generateKey();
261
262        // put the key into keystore
263        String alias = "alias";
264        keyStore.setKeyEntry(alias, secretKey, "pwd".toCharArray(), null);
265
266        // check if it is a secret key
267        assertTrue(keyStore.entryInstanceOf(alias,
268                KeyStore.SecretKeyEntry.class));
269
270        // check if it is NOT a private key
271        assertFalse(keyStore.entryInstanceOf(alias,
272                KeyStore.PrivateKeyEntry.class));
273    }
274
275    /**
276     * @tests java.security.KeyStore.TrustedCertificateEntry.toString()
277     */
278    public void testKeyStoreTCToString() {
279    	   // Regression for HARMONY-1542
280    	   // no exception expected
281        class TestX509Certificate extends X509Certificate {
282            private static final long serialVersionUID = 1L;
283            public void checkValidity() throws CertificateExpiredException,CertificateNotYetValidException {}
284            public void checkValidity(Date p) throws CertificateExpiredException, CertificateNotYetValidException {}
285            public int getVersion() {
286                    return 0;
287            }
288            public BigInteger getSerialNumber() {
289                    return null;
290            }
291            public Principal getIssuerDN() {
292                    return null;
293            }
294            public Principal getSubjectDN() {
295                    return null;
296            }
297            public Date getNotBefore() {
298                    return null;
299            }
300            public Date getNotAfter() {
301                    return null;
302            }
303            public byte[] getTBSCertificate() throws CertificateEncodingException {
304                    return null;
305            }
306            public byte[] getSignature() {
307                    return null;
308            }
309            public String getSigAlgName() {
310                    return null;
311            }
312            public String getSigAlgOID() {
313                    return null;
314            }
315            public byte[] getSigAlgParams() {
316                    return null;
317            }
318            public boolean[] getIssuerUniqueID() {
319                    return null;
320            }
321            public boolean[] getSubjectUniqueID() {
322                    return null;
323            }
324            public boolean[] getKeyUsage() {
325                    return null;
326            }
327            public int getBasicConstraints() {
328                    return 0;
329            }
330            public byte[] getEncoded() throws CertificateEncodingException {
331                    return null;
332            }
333            public void verify(PublicKey p)
334                    throws CertificateException,
335                    NoSuchAlgorithmException,
336                    InvalidKeyException,
337                    NoSuchProviderException,
338                    SignatureException
339            {}
340            public void verify(PublicKey p0, String p1)
341                    throws CertificateException,
342                    NoSuchAlgorithmException,
343                    InvalidKeyException,
344                    NoSuchProviderException,
345                    SignatureException
346            {}
347            public String toString() {
348                    return null;
349            }
350            public PublicKey getPublicKey() {
351                    return null;
352            }
353            public boolean hasUnsupportedCriticalExtension() {
354                    return false;
355            }
356            public Set getCriticalExtensionOIDs() {
357                    return null;
358            }
359            public Set getNonCriticalExtensionOIDs() {
360                    return null;
361            }
362            public byte[] getExtensionValue(String p) {
363                    return null;
364            }
365        }
366        assertNotNull(new KeyStore.TrustedCertificateEntry(new TestX509Certificate()).toString());
367    }
368}
369