SealedObjectTest.java revision 89c1feb0a69a7707b271086e749975b3f7acacf7
1/*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with this
4 * work for additional information regarding copyright ownership. The ASF
5 * licenses this file to You under the Apache License, Version 2.0 (the
6 * "License"); you may not use this file except in compliance with the License.
7 * 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, WITHOUT
13 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14 * License for the specific language governing permissions and limitations under
15 * the License.
16 */
17
18/**
19 * @author Alexander Y. Kleymenov
20 * @version $Revision$
21 */
22
23package org.apache.harmony.crypto.tests.javax.crypto;
24
25import dalvik.annotation.TestTargetClass;
26import dalvik.annotation.TestInfo;
27import dalvik.annotation.TestLevel;
28import dalvik.annotation.TestTarget;
29
30import java.io.ByteArrayInputStream;
31import java.io.ByteArrayOutputStream;
32import java.io.IOException;
33import java.io.ObjectInputStream;
34import java.io.ObjectOutputStream;
35import java.io.Serializable;
36import java.security.Key;
37import java.util.Arrays;
38import javax.crypto.Cipher;
39import javax.crypto.IllegalBlockSizeException;
40import javax.crypto.KeyGenerator;
41import javax.crypto.NullCipher;
42import javax.crypto.SealedObject;
43import javax.crypto.spec.IvParameterSpec;
44import javax.crypto.spec.SecretKeySpec;
45
46import junit.framework.TestCase;
47
48@TestTargetClass(SealedObject.class)
49/**
50 */
51public class SealedObjectTest extends TestCase {
52    class Mock_SealedObject extends SealedObject {
53        public Mock_SealedObject(Serializable object, Cipher c)
54                throws IOException, IllegalBlockSizeException {
55            super(object, c);
56        }
57
58        public byte[] get_encodedParams() {
59            return super.encodedParams;
60        }
61
62    }
63
64    /**
65     * readObject(ObjectInputStream s) method testing. Tests if the
66     * serialization/deserialization works correctly: object is serialized,
67     * deserialized, the content od deserialized object equals to the content of
68     * initial object.
69     */
70@TestInfo(
71      level = TestLevel.COMPLETE,
72      purpose = "",
73      targets = {
74        @TestTarget(
75          methodName = "!Serialization",
76          methodArgs = {}
77        )
78    })
79    public void testReadObject() throws Exception {
80        String secret = "secret string";
81        SealedObject so = new SealedObject(secret, new NullCipher());
82        ByteArrayOutputStream bos = new ByteArrayOutputStream();
83        ObjectOutputStream oos = new ObjectOutputStream(bos);
84        oos.writeObject(so);
85
86        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(
87                bos.toByteArray()));
88
89        SealedObject so_des = (SealedObject) ois.readObject();
90        assertEquals("The secret content of deserialized object "
91                + "should be equal to the secret content of initial object",
92                secret, so_des.getObject(new NullCipher()));
93        assertEquals("The value returned by getAlgorithm() method of "
94                + "deserialized object should be equal to the value returned "
95                + "by getAlgorithm() method of initial object", so
96                .getAlgorithm(), so_des.getAlgorithm());
97    }
98
99    /**
100     * SealedObject(Serializable object, Cipher c) method testing. Tests if the
101     * NullPointerException is thrown in the case of null cipher.
102     */
103@TestInfo(
104      level = TestLevel.PARTIAL,
105      purpose = "Functionality checked in testSealedObject2, missed IOException & IllegalBlockSizeException checking",
106      targets = {
107        @TestTarget(
108          methodName = "SealedObject",
109          methodArgs = {java.io.Serializable.class, javax.crypto.Cipher.class}
110        )
111    })
112    public void testSealedObject1() throws Exception {
113        String secret = "secret string";
114        try {
115            new SealedObject(secret, null);
116            fail("NullPointerException should be thrown in the case "
117                    + "of null cipher.");
118        } catch (NullPointerException e) {
119        }
120    }
121
122    /**
123     * SealedObject(SealedObject so) method testing. Tests if the
124     * NullPointerException is thrown in the case of null SealedObject.
125     */
126@TestInfo(
127      level = TestLevel.COMPLETE,
128      purpose = "",
129      targets = {
130        @TestTarget(
131          methodName = "SealedObject",
132          methodArgs = {javax.crypto.SealedObject.class}
133        )
134    })
135    public void testSealedObject2() throws Exception {
136        try {
137            new SealedObject(null) {};
138            fail("NullPointerException should be thrown in the case "
139                    + "of null SealedObject.");
140        } catch (NullPointerException e) {
141        }
142
143        String secret = "secret string";
144        Cipher cipher = new NullCipher();
145        SealedObject so1 = new SealedObject(secret, cipher);
146        SealedObject so2 = new SealedObject(so1) {};
147
148        assertEquals("The secret content of the object should equals "
149                + "to the secret content of initial object.", secret, so2
150                .getObject(cipher));
151        assertEquals("The algorithm which was used to seal the object "
152                + "should be the same as the algorithm used to seal the "
153                + "initial object", so1.getAlgorithm(), so2.getAlgorithm());
154    }
155
156    /**
157     * getAlgorithm() method testing. Tests if the returned value equals to the
158     * corresponding value of Cipher object.
159     */
160@TestInfo(
161      level = TestLevel.COMPLETE,
162      purpose = "",
163      targets = {
164        @TestTarget(
165          methodName = "getAlgorithm",
166          methodArgs = {}
167        )
168    })
169    public void testGetAlgorithm() throws Exception {
170        String secret = "secret string";
171        String algorithm = "DES";
172        KeyGenerator kg = KeyGenerator.getInstance(algorithm);
173        Key key = kg.generateKey();
174
175        Cipher cipher = Cipher.getInstance(algorithm);
176        cipher.init(Cipher.ENCRYPT_MODE, key);
177        SealedObject so = new SealedObject(secret, cipher);
178
179        assertEquals("The algorithm name should be the same as used "
180                + "in cipher.", algorithm, so.getAlgorithm());
181    }
182
183    /**
184     * getObject(Key key) method testing. Tests if the object sealed with
185     * encryption algorithm and specified parameters can be retrieved by
186     * specifying the cryptographic key.
187     */
188@TestInfo(
189      level = TestLevel.PARTIAL,
190      purpose = "Exceptions checking missed.",
191      targets = {
192        @TestTarget(
193          methodName = "getObject",
194          methodArgs = {java.security.Key.class}
195        )
196    })
197    public void testGetObject1() throws Exception {
198        KeyGenerator kg = KeyGenerator.getInstance("DES");
199        Key key = kg.generateKey();
200
201        IvParameterSpec ips = new IvParameterSpec(new byte[] {
202                1, 2, 3, 4, 5, 6, 7, 8});
203
204        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
205        cipher.init(Cipher.ENCRYPT_MODE, key, ips);
206
207        String secret = "secret string";
208        Mock_SealedObject so = new Mock_SealedObject(secret, cipher);
209
210        assertEquals("The returned object does not equals to the "
211                + "original object.", secret, so.getObject(key));
212
213        assertTrue("The encodedParams field of SealedObject object "
214                + "should contain the encoded algorithm parameters.", Arrays
215                .equals(so.get_encodedParams(), cipher.getParameters()
216                        .getEncoded()));
217    }
218
219    /**
220     * getObject(Cipher c) method testing. Tests if the proper exception is
221     * thrown in the case of incorrect input parameters and if the object sealed
222     * with encryption algorithm and specified parameters can be retrieved by
223     * specifying the initialized Cipher object.
224     */
225@TestInfo(
226      level = TestLevel.PARTIAL,
227      purpose = "Exceptions checking missed.",
228      targets = {
229        @TestTarget(
230          methodName = "getObject",
231          methodArgs = {javax.crypto.Cipher.class}
232        )
233    })
234    public void testGetObject2() throws Exception {
235        try {
236            new SealedObject("secret string", new NullCipher())
237                    .getObject((Cipher) null);
238            fail("NullPointerException should be thrown in the case of "
239                    + "null cipher.");
240        } catch (NullPointerException e) {
241        }
242
243        KeyGenerator kg = KeyGenerator.getInstance("DES");
244        Key key = kg.generateKey();
245
246        IvParameterSpec ips = new IvParameterSpec(new byte[] {
247                1, 2, 3, 4, 5, 6, 7, 8});
248
249        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
250        cipher.init(Cipher.ENCRYPT_MODE, key, ips);
251
252        String secret = "secret string";
253        SealedObject so = new SealedObject(secret, cipher);
254
255        cipher.init(Cipher.DECRYPT_MODE, key, ips);
256        assertEquals("The returned object does not equals to the "
257                + "original object.", secret, so.getObject(cipher));
258    }
259
260    /**
261     * getObject(Key key, String provider) method testing. Tests if the proper
262     * exception is thrown in the case of incorrect input parameters and if the
263     * object sealed with encryption algorithm can be retrieved by specifying
264     * the cryptographic key and provider name.
265     */
266@TestInfo(
267      level = TestLevel.PARTIAL,
268      purpose = "Exceptions checking missed.",
269      targets = {
270        @TestTarget(
271          methodName = "getObject",
272          methodArgs = {java.security.Key.class, java.lang.String.class}
273        )
274    })
275    public void testGetObject3() throws Exception {
276        try {
277            new SealedObject("secret string", new NullCipher()).getObject(
278                    new SecretKeySpec(new byte[] {0, 0, 0}, "algorithm"), null);
279            fail("IllegalArgumentException should be thrown in the case of "
280                    + "null provider.");
281        } catch (IllegalArgumentException e) {
282        }
283
284        try {
285            new SealedObject("secret string", new NullCipher()).getObject(
286                    new SecretKeySpec(new byte[] {0, 0, 0}, "algorithm"), "");
287            fail("IllegalArgumentException should be thrown in the case of "
288                    + "empty provider.");
289        } catch (IllegalArgumentException e) {
290        }
291
292        KeyGenerator kg = KeyGenerator.getInstance("DES");
293        Key key = kg.generateKey();
294
295        Cipher cipher = Cipher.getInstance("DES");
296        String provider = cipher.getProvider().getName();
297        cipher.init(Cipher.ENCRYPT_MODE, key);
298
299        String secret = "secret string";
300        SealedObject so = new SealedObject(secret, cipher);
301
302        cipher.init(Cipher.DECRYPT_MODE, key);
303        assertEquals("The returned object does not equals to the "
304                + "original object.", secret, so.getObject(key, provider));
305    }
306
307}
308