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.crypto.tests.javax.crypto;
19
20import dalvik.annotation.TestLevel;
21import dalvik.annotation.TestTargetClass;
22import dalvik.annotation.TestTargetNew;
23import dalvik.annotation.TestTargets;
24
25import org.apache.harmony.crypto.tests.support.MyCipher;
26
27import tests.support.resource.Support_Resources;
28import tests.util.TestEnvironment;
29
30import java.io.ByteArrayOutputStream;
31import java.io.File;
32import java.io.IOException;
33import java.io.InputStream;
34import java.math.BigInteger;
35import java.net.MalformedURLException;
36import java.net.URL;
37import java.nio.ByteBuffer;
38import java.nio.ReadOnlyBufferException;
39import java.security.AlgorithmParameters;
40import java.security.InvalidAlgorithmParameterException;
41import java.security.InvalidKeyException;
42import java.security.Key;
43import java.security.NoSuchAlgorithmException;
44import java.security.NoSuchProviderException;
45import java.security.Provider;
46import java.security.SecureRandom;
47import java.security.Security;
48import java.security.cert.Certificate;
49import java.security.cert.CertificateException;
50import java.security.cert.CertificateFactory;
51import java.security.spec.AlgorithmParameterSpec;
52import java.security.spec.RSAKeyGenParameterSpec;
53import java.util.Arrays;
54
55import javax.crypto.BadPaddingException;
56import javax.crypto.Cipher;
57import javax.crypto.CipherSpi;
58import javax.crypto.IllegalBlockSizeException;
59import javax.crypto.KeyGenerator;
60import javax.crypto.NoSuchPaddingException;
61import javax.crypto.SecretKeyFactory;
62import javax.crypto.ShortBufferException;
63import javax.crypto.spec.DESedeKeySpec;
64import javax.crypto.spec.IvParameterSpec;
65
66@TestTargetClass(Cipher.class)
67public class CipherTest extends junit.framework.TestCase {
68
69    static Key cipherKey;
70    static final String algorithm = "DESede";
71    static final int keyLen = 168;
72
73    static Key cipherKeyDES;
74    static final String algorithmDES = "DES";
75    static final int keyLenDES = 56;
76
77    static {
78        try {
79            KeyGenerator kg = KeyGenerator.getInstance(algorithm);
80            kg.init(keyLen, new SecureRandom());
81            cipherKey = kg.generateKey();
82
83            kg = KeyGenerator.getInstance(algorithmDES);
84            kg.init(keyLenDES, new SecureRandom());
85            cipherKeyDES = kg.generateKey();
86        } catch (Exception e) {
87            fail("No key " + e);
88        }
89    }
90
91    @Override protected void setUp() throws Exception {
92        super.setUp();
93        TestEnvironment.reset();
94    }
95
96    /**
97     * @tests javax.crypto.Cipher#getInstance(java.lang.String)
98     */
99    @TestTargets({
100        @TestTargetNew(
101            level = TestLevel.COMPLETE,
102            notes = "",
103            method = "getInstance",
104            args = {java.lang.String.class}
105        ),
106        @TestTargetNew(
107            level = TestLevel.COMPLETE,
108            notes = "",
109            clazz = CipherSpi.class,
110            method = "engineSetMode",
111            args = {java.lang.String.class}
112        ),
113        @TestTargetNew(
114            level = TestLevel.COMPLETE,
115            notes = "",
116            clazz = CipherSpi.class,
117            method = "engineSetPadding",
118            args = {java.lang.String.class}
119        )
120    })
121    public void test_getInstanceLjava_lang_String() throws Exception {
122        Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
123        assertNotNull("Received a null Cipher instance", cipher);
124
125        try {
126            Cipher.getInstance("WrongAlgorithmName");
127            fail("NoSuchAlgorithmException expected");
128        } catch (NoSuchAlgorithmException e) {
129            //expected
130        }
131//        RI throws  NoSuchAlgorithmException for wrong padding.
132    }
133
134    /**
135     * @tests javax.crypto.Cipher#getInstance(java.lang.String,
136     *        java.lang.String)
137     */
138    @TestTargets({
139        @TestTargetNew(
140            level = TestLevel.COMPLETE,
141            notes = "",
142            method = "getInstance",
143            args = {java.lang.String.class, java.lang.String.class}
144        ),
145        @TestTargetNew(
146            level = TestLevel.COMPLETE,
147            notes = "",
148            clazz = CipherSpi.class,
149            method = "engineSetMode",
150            args = {java.lang.String.class}
151        ),
152        @TestTargetNew(
153            level = TestLevel.COMPLETE,
154            notes = "",
155            clazz = CipherSpi.class,
156            method = "engineSetPadding",
157            args = {java.lang.String.class}
158        )
159    })
160    public void test_getInstanceLjava_lang_StringLjava_lang_String()
161            throws Exception {
162
163        Provider[] providers = Security.getProviders("Cipher.DES");
164
165        assertNotNull("No installed providers support Cipher.DES", providers);
166
167        for (int i = 0; i < providers.length; i++) {
168            Cipher cipher = Cipher.getInstance("DES", providers[i].getName());
169            assertNotNull("Cipher.getInstance() returned a null value", cipher);
170
171            // Exception case
172            try {
173                cipher = Cipher.getInstance("DoBeDoBeDo", providers[i]);
174                fail("Should have thrown an NoSuchAlgorithmException");
175            } catch (NoSuchAlgorithmException e) {
176                // Expected
177            }
178        }
179
180        // Exception case
181        try {
182            Cipher.getInstance("DES", (String) null);
183            fail("Should have thrown an IllegalArgumentException");
184        } catch (IllegalArgumentException e) {
185            // Expected
186        }
187
188        // Exception case
189        try {
190            Cipher.getInstance("DES", "IHaveNotBeenConfigured");
191            fail("Should have thrown an NoSuchProviderException");
192        } catch (NoSuchProviderException e) {
193            // Expected
194        }
195//      RI throws  NoSuchAlgorithmException for wrong padding.
196    }
197
198    /**
199     * @tests javax.crypto.Cipher#getInstance(java.lang.String,
200     *        java.security.Provider)
201     */
202    @TestTargets({
203        @TestTargetNew(
204            level = TestLevel.COMPLETE,
205            notes = "",
206            method = "getInstance",
207            args = {java.lang.String.class, java.security.Provider.class}
208        ),
209        @TestTargetNew(
210            level = TestLevel.COMPLETE,
211            notes = "",
212            clazz = CipherSpi.class,
213            method = "engineSetMode",
214            args = {java.lang.String.class}
215        ),
216        @TestTargetNew(
217            level = TestLevel.COMPLETE,
218            notes = "",
219            clazz = CipherSpi.class,
220            method = "engineSetPadding",
221            args = {java.lang.String.class}
222        )
223    })
224    public void test_getInstanceLjava_lang_StringLjava_security_Provider()
225            throws Exception {
226
227        Provider[] providers = Security.getProviders("Cipher.DES");
228
229        assertNotNull("No installed providers support Cipher.DES", providers);
230
231        for (int i = 0; i < providers.length; i++) {
232            Cipher cipher = Cipher.getInstance("DES", providers[i]);
233            assertNotNull("Cipher.getInstance() returned a null value", cipher);
234        }
235
236        // Exception case
237        try {
238            Cipher.getInstance("DES", (Provider) null);
239            fail("Should have thrown an IllegalArgumentException");
240        } catch (IllegalArgumentException e) {
241            // Expected
242        }
243
244        // Exception case
245        try {
246            Cipher.getInstance("WrongAlg", providers[0]);
247            fail("NoSuchAlgorithmException expected");
248        } catch (NoSuchAlgorithmException e) {
249            // Expected
250        }
251//      RI throws  NoSuchAlgorithmException for wrong padding.
252    }
253
254    /**
255     * @tests javax.crypto.Cipher#getProvider()
256     */
257    @TestTargetNew(
258        level = TestLevel.COMPLETE,
259        notes = "",
260        method = "getProvider",
261        args = {}
262    )
263    public void test_getProvider() throws Exception {
264
265        Provider[] providers = Security.getProviders("Cipher.AES");
266
267        assertNotNull("No providers support Cipher.AES", providers);
268
269        for (int i = 0; i < providers.length; i++) {
270            Provider provider = providers[i];
271            Cipher cipher = Cipher.getInstance("AES", provider.getName());
272            Provider cipherProvider = cipher.getProvider();
273            assertTrue("Cipher provider is not the same as that "
274                    + "provided as parameter to getInstance()", cipherProvider
275                    .equals(provider));
276        }
277    }
278
279    /**
280     * @tests javax.crypto.Cipher#getAlgorithm()
281     */
282    @TestTargetNew(
283        level = TestLevel.COMPLETE,
284        notes = "",
285        method = "getAlgorithm",
286        args = {}
287    )
288    public void test_getAlgorithm() throws Exception {
289        final String algorithm = "DESede/CBC/PKCS5Padding";
290
291        Cipher cipher = Cipher.getInstance(algorithm);
292        assertTrue("Cipher algorithm does not match", cipher.getAlgorithm()
293                .equals(algorithm));
294    }
295
296    /**
297     * @tests javax.crypto.Cipher#getBlockSize()
298     */
299    @TestTargets({
300        @TestTargetNew(
301            level = TestLevel.COMPLETE,
302            notes = "",
303            method = "getBlockSize",
304            args = {}
305        ),
306        @TestTargetNew(
307            level = TestLevel.COMPLETE,
308            notes = "",
309            clazz = CipherSpi.class,
310            method = "engineGetBlockSize",
311            args = {}
312        )
313    })
314    public void test_getBlockSize() throws Exception {
315        final String algorithm = "DESede/CBC/PKCS5Padding";
316
317        Cipher cipher = Cipher.getInstance(algorithm);
318        assertEquals("Block size does not match", 8, cipher.getBlockSize());
319    }
320
321    /**
322     * @tests javax.crypto.Cipher#getOutputSize(int)
323     */
324    @TestTargets({
325        @TestTargetNew(
326            level = TestLevel.COMPLETE,
327            notes = "",
328            method = "getOutputSize",
329            args = {int.class}
330        ),
331        @TestTargetNew(
332            level = TestLevel.COMPLETE,
333            notes = "",
334            clazz = CipherSpi.class,
335            method = "engineGetOutputSize",
336            args = {int.class}
337        )
338    })
339    public void test_getOutputSizeI() throws Exception {
340
341        SecureRandom sr = new SecureRandom();
342        Cipher cipher = Cipher.getInstance(algorithm + "/ECB/PKCS5Padding");
343
344        try {
345            cipher.getOutputSize(25);
346            fail("IllegalStateException expected");
347        } catch (IllegalStateException e) {
348            //expected
349        }
350
351        cipher.init(Cipher.ENCRYPT_MODE, cipherKey, sr);
352
353        // A 25-byte input could result in at least 4 8-byte blocks
354        int result = cipher.getOutputSize(25);
355        assertTrue("Output size too small", result > 31);
356
357        // A 8-byte input should result in 2 8-byte blocks
358        result = cipher.getOutputSize(8);
359        assertTrue("Output size too small", result > 15);
360    }
361
362    /**
363     * @tests javax.crypto.Cipher#init(int, java.security.Key)
364     */
365    @TestTargetNew(
366        level = TestLevel.COMPLETE,
367        notes = "",
368        method = "init",
369        args = {int.class, java.security.Key.class}
370    )
371    public void test_initILjava_security_Key() throws Exception {
372        Cipher cipher = Cipher.getInstance(algorithm + "/ECB/PKCS5Padding");
373        cipher.init(Cipher.ENCRYPT_MODE, cipherKey);
374
375
376        cipher = Cipher.getInstance("DES/CBC/NoPadding");
377        try {
378            cipher.init(Cipher.ENCRYPT_MODE, cipherKey);
379            fail("InvalidKeyException expected");
380        } catch (InvalidKeyException e) {
381            //expected
382        }
383    }
384
385    /**
386     * @tests javax.crypto.Cipher#init(int, java.security.Key,
387     *        java.security.SecureRandom)
388     */
389    @TestTargets({
390        @TestTargetNew(
391            level = TestLevel.COMPLETE,
392            notes = "",
393            method = "init",
394            args = {int.class, java.security.Key.class, java.security.SecureRandom.class}
395        ),
396        @TestTargetNew(
397            level = TestLevel.COMPLETE,
398            notes = "",
399            clazz = CipherSpi.class,
400            method = "engineInit",
401            args = {int.class, java.security.Key.class, java.security.SecureRandom.class}
402        )
403    })
404    public void test_initILjava_security_KeyLjava_security_SecureRandom()
405            throws Exception {
406        SecureRandom sr = new SecureRandom();
407        Cipher cipher = Cipher.getInstance(algorithm + "/ECB/PKCS5Padding");
408        cipher.init(Cipher.ENCRYPT_MODE, cipherKey, sr);
409
410        cipher = Cipher.getInstance("DES/CBC/NoPadding");
411        try {
412            cipher.init(Cipher.ENCRYPT_MODE, cipherKey, sr);
413            fail("InvalidKeyException expected");
414        } catch (InvalidKeyException e) {
415            //expected
416        }
417    }
418
419    /**
420     * @tests javax.crypto.Cipher#init(int, java.security.Key,
421     *        java.security.spec.AlgorithmParameterSpec)
422     */
423    @TestTargetNew(
424        level = TestLevel.COMPLETE,
425        notes = "",
426        method = "init",
427        args = {int.class, java.security.Key.class, java.security.spec.AlgorithmParameterSpec.class}
428    )
429    public void test_initILjava_security_KeyLjava_security_spec_AlgorithmParameterSpec()
430            throws Exception {
431        SecureRandom sr = new SecureRandom();
432        Cipher cipher = null;
433
434        byte[] iv = null;
435        AlgorithmParameterSpec ap = null;
436
437        iv = new byte[8];
438        sr.nextBytes(iv);
439        ap = new IvParameterSpec(iv);
440
441        cipher = Cipher.getInstance(algorithm + "/CBC/PKCS5Padding");
442
443        cipher.init(Cipher.ENCRYPT_MODE, cipherKey, ap);
444
445        byte[] cipherIV = cipher.getIV();
446
447        assertTrue("IVs differ", Arrays.equals(cipherIV, iv));
448
449        cipher = Cipher.getInstance("DES/CBC/NoPadding");
450        try {
451            cipher.init(Cipher.ENCRYPT_MODE, cipherKey, ap);
452            fail("InvalidKeyException expected");
453        } catch (InvalidKeyException e) {
454            //expected
455        }
456
457        cipher = Cipher.getInstance("DES/CBC/NoPadding");
458        ap = new RSAKeyGenParameterSpec(10, new BigInteger("10"));
459
460        try {
461            cipher.init(Cipher.ENCRYPT_MODE, cipherKeyDES, ap);
462            fail("InvalidAlgorithmParameterException expected");
463        } catch (InvalidAlgorithmParameterException e) {
464            //expected
465        }
466    }
467
468    /**
469     * @tests javax.crypto.Cipher#init(int, java.security.Key,
470     *        java.security.spec.AlgorithmParameterSpec,
471     *        java.security.SecureRandom)
472     */
473    @TestTargets({
474        @TestTargetNew(
475            level = TestLevel.COMPLETE,
476            notes = "",
477            method = "init",
478            args = {int.class, java.security.Key.class, java.security.spec.AlgorithmParameterSpec.class, java.security.SecureRandom.class}
479        ),
480        @TestTargetNew(
481            level = TestLevel.COMPLETE,
482            notes = "",
483            clazz = CipherSpi.class,
484            method = "engineInit",
485            args = {int.class, java.security.Key.class, java.security.spec.AlgorithmParameterSpec.class, java.security.SecureRandom.class}
486        )
487    })
488    public void test_initILjava_security_KeyLjava_security_spec_AlgorithmParameterSpecLjava_security_SecureRandom()
489            throws Exception {
490        SecureRandom sr = new SecureRandom();
491        Cipher cipher = null;
492
493        byte[] iv = null;
494        AlgorithmParameterSpec ap = null;
495
496        iv = new byte[8];
497        sr.nextBytes(iv);
498        ap = new IvParameterSpec(iv);
499
500        cipher = Cipher.getInstance(algorithm + "/CBC/PKCS5Padding");
501
502        cipher.init(Cipher.ENCRYPT_MODE, cipherKey, ap, sr);
503
504        byte[] cipherIV = cipher.getIV();
505
506        assertTrue("IVs differ", Arrays.equals(cipherIV, iv));
507        cipher = Cipher.getInstance("DES/CBC/NoPadding");
508        try {
509            cipher.init(Cipher.ENCRYPT_MODE, cipherKey, ap, sr);
510            fail("InvalidKeyException expected");
511        } catch (InvalidKeyException e) {
512            //expected
513        }
514
515        cipher = Cipher.getInstance("DES/CBC/NoPadding");
516        ap = new RSAKeyGenParameterSpec(10, new BigInteger("10"));
517
518        try {
519            cipher.init(Cipher.ENCRYPT_MODE, cipherKeyDES, ap, sr);
520            fail("InvalidAlgorithmParameterException expected");
521        } catch (InvalidAlgorithmParameterException e) {
522            //expected
523        }
524    }
525
526    /**
527     * @tests javax.crypto.Cipher#update(byte[], int, int)
528     */
529    @TestTargets({
530        @TestTargetNew(
531            level = TestLevel.COMPLETE,
532            notes = "",
533            method = "update",
534            args = {byte[].class, int.class, int.class}
535        ),
536        @TestTargetNew(
537            level = TestLevel.COMPLETE,
538            notes = "",
539            clazz = CipherSpi.class,
540            method = "engineUpdate",
541            args = {byte[].class, int.class, int.class}
542        )
543    })
544    public void test_update$BII() throws Exception {
545        for (int index = 1; index < 4; index++) {
546            Cipher c = Cipher.getInstance("DESEDE/CBC/PKCS5Padding");
547
548            byte[] keyMaterial = loadBytes("hyts_" + "des-ede3-cbc.test"
549                    + index + ".key");
550            DESedeKeySpec keySpec = new DESedeKeySpec(keyMaterial);
551            SecretKeyFactory skf = SecretKeyFactory.getInstance("DESEDE");
552            Key k = skf.generateSecret(keySpec);
553
554            byte[] ivMaterial = loadBytes("hyts_" + "des-ede3-cbc.test" + index
555                    + ".iv");
556            IvParameterSpec iv = new IvParameterSpec(ivMaterial);
557
558            c.init(Cipher.DECRYPT_MODE, k, iv);
559
560            ByteArrayOutputStream baos = new ByteArrayOutputStream();
561            byte[] input = new byte[256];
562            String resPath = "hyts_" + "des-ede3-cbc.test" + index
563                    + ".ciphertext";
564            File resources = Support_Resources.createTempFolder();
565            Support_Resources.copyFile(resources, null, resPath);
566            InputStream is = Support_Resources.getStream(resPath);
567
568            int bytesRead = is.read(input, 0, 256);
569            while (bytesRead > 0) {
570                byte[] output = c.update(input, 0, bytesRead);
571                if (output != null) {
572                    baos.write(output);
573                }
574                bytesRead = is.read(input, 0, 256);
575            }
576
577            byte[] output = c.doFinal();
578            if (output != null) {
579                baos.write(output);
580            }
581
582            byte[] decipheredCipherText = baos.toByteArray();
583            is.close();
584
585            byte[] plaintextBytes = loadBytes("hyts_" + "des-ede3-cbc.test"
586                    + index + ".plaintext");
587            assertTrue("Operation produced incorrect results", Arrays.equals(
588                    plaintextBytes, decipheredCipherText));
589        }// end for
590
591        Cipher cipher = Cipher.getInstance("DESEDE/CBC/PKCS5Padding");
592        try {
593            cipher.update(new byte[64], 0, 32);
594            fail("IllegalStateException expected");
595        } catch (IllegalStateException e) {
596            //expected
597        }
598    }
599
600    /**
601     * @tests javax.crypto.Cipher#doFinal()
602     */
603    @TestTargetNew(
604        level = TestLevel.COMPLETE,
605        notes = "",
606        method = "doFinal",
607        args = {}
608    )
609    public void test_doFinal() throws Exception {
610        for (int index = 1; index < 4; index++) {
611            Cipher c = Cipher.getInstance("DESEDE/CBC/PKCS5Padding");
612
613            byte[] keyMaterial = loadBytes("hyts_" + "des-ede3-cbc.test"
614                    + index + ".key");
615            DESedeKeySpec keySpec = new DESedeKeySpec(keyMaterial);
616            SecretKeyFactory skf = SecretKeyFactory.getInstance("DESEDE");
617            Key k = skf.generateSecret(keySpec);
618
619            byte[] ivMaterial = loadBytes("hyts_" + "des-ede3-cbc.test" + index
620                    + ".iv");
621            IvParameterSpec iv = new IvParameterSpec(ivMaterial);
622
623            c.init(Cipher.ENCRYPT_MODE, k, iv);
624
625            ByteArrayOutputStream baos = new ByteArrayOutputStream();
626            byte[] input = new byte[256];
627            String resPath = "hyts_" + "des-ede3-cbc.test" + index
628                    + ".plaintext";
629            File resources = Support_Resources.createTempFolder();
630            Support_Resources.copyFile(resources, null, resPath);
631            InputStream is = Support_Resources.getStream(resPath);
632
633            int bytesRead = is.read(input, 0, 256);
634            while (bytesRead > 0) {
635                byte[] output = c.update(input, 0, bytesRead);
636                if (output != null) {
637                    baos.write(output);
638                }
639                bytesRead = is.read(input, 0, 256);
640            }
641            byte[] output = c.doFinal();
642            if (output != null) {
643                baos.write(output);
644            }
645            byte[] encryptedPlaintext = baos.toByteArray();
646            is.close();
647
648            byte[] cipherText = loadBytes("hyts_" + "des-ede3-cbc.test" + index
649                    + ".ciphertext");
650            assertTrue("Operation produced incorrect results", Arrays.equals(
651                    encryptedPlaintext, cipherText));
652        }// end for
653
654        byte[] b = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
655        byte[] b1 = new byte[30];
656
657        Cipher c = Cipher.getInstance("DES/CBC/NoPadding");
658        c.init(Cipher.ENCRYPT_MODE, cipherKeyDES);
659        c.update(b, 0, 10, b1, 5);
660        try {
661            c.doFinal();
662            fail("IllegalBlockSizeException expected");
663        } catch (IllegalBlockSizeException e) {
664            //expected
665        }
666
667        c = Cipher.getInstance("DES/CBC/NoPadding");
668        try {
669            c.doFinal();
670            fail("IllegalStateException expected");
671        } catch (IllegalStateException e) {
672            //expected
673        }
674
675        c = Cipher.getInstance("DES/CBC/NoPadding");
676        c.init(Cipher.ENCRYPT_MODE, cipherKeyDES);
677        c.doFinal(b, 0, 16, b1, 0);
678
679        SecureRandom sr = new SecureRandom();
680        byte[] iv = new byte[8];
681        sr.nextBytes(iv);
682        AlgorithmParameterSpec ap = new IvParameterSpec(iv);
683
684        c = Cipher.getInstance("DES/CBC/PKCS5Padding");
685        c.init(Cipher.DECRYPT_MODE, cipherKeyDES, ap);
686
687        c.update(b1, 0, 24, b, 0);
688        try {
689            c.doFinal();
690            fail("BadPaddingException expected");
691        } catch (BadPaddingException e) {
692            //expected
693        }
694    }
695
696    private byte[] loadBytes(String resPath) {
697        try {
698            File resources = Support_Resources.createTempFolder();
699            Support_Resources.copyFile(resources, null, resPath);
700            InputStream is = Support_Resources.getStream(resPath);
701
702            ByteArrayOutputStream out = new ByteArrayOutputStream();
703            byte[] buff = new byte[1024];
704            int readlen;
705            while ((readlen = is.read(buff)) > 0) {
706                out.write(buff, 0, readlen);
707            }
708            is.close();
709            return out.toByteArray();
710        } catch (IOException e) {
711            return null;
712        }
713    }
714
715    @TestTargets({
716        @TestTargetNew(
717            level = TestLevel.COMPLETE,
718            notes = "",
719            method = "getParameters",
720            args = {}
721        ),
722        @TestTargetNew(
723            level = TestLevel.COMPLETE,
724            notes = "",
725            clazz = CipherSpi.class,
726            method = "engineGetParameters",
727            args = {}
728        )
729    })
730    public void testGetParameters() throws Exception {
731        Cipher c = Cipher.getInstance("DES");
732        assertNull(c.getParameters());
733    }
734
735    /*
736     * Class under test for int update(byte[], int, int, byte[], int)
737     */
738    @TestTargets({
739        @TestTargetNew(
740            level = TestLevel.COMPLETE,
741            notes = "",
742            method = "update",
743            args = {byte[].class, int.class, int.class, byte[].class, int.class}
744        ),
745        @TestTargetNew(
746            level = TestLevel.COMPLETE,
747            notes = "",
748            clazz = CipherSpi.class,
749            method = "engineUpdate",
750            args = {byte[].class, int.class, int.class, byte[].class, int.class}
751        )
752    })
753    public void testUpdatebyteArrayintintbyteArrayint() throws Exception {
754        byte[] b = {1,2,3,4,5,6,7,8,9,10};
755        byte[] b1 = new byte[6];
756        Cipher c = Cipher.getInstance("DESede");
757
758        try {
759            c.update(b, 0, 10, b1, 5);
760            fail("IllegalStateException expected");
761        } catch (IllegalStateException e) {
762            //expected
763        }
764
765        c.init(Cipher.ENCRYPT_MODE, cipherKey);
766        try {
767            c.update(b, 0, 10, b1, 5);
768            fail("ShortBufferException expected");
769        } catch (ShortBufferException e) {
770            //expected
771        }
772
773        b1 = new byte[30];
774        c.update(b, 0, 10, b1, 5);
775    }
776
777    /*
778     * Class under test for int doFinal(byte[], int, int, byte[], int)
779     */
780    @TestTargets({
781        @TestTargetNew(
782            level = TestLevel.COMPLETE,
783            notes = "",
784            method = "doFinal",
785            args = {byte[].class, int.class, int.class, byte[].class, int.class}
786        ),
787        @TestTargetNew(
788            level = TestLevel.COMPLETE,
789            notes = "",
790            clazz = CipherSpi.class,
791            method = "engineDoFinal",
792            args = {byte[].class, int.class, int.class, byte[].class, int.class}
793        )
794    })
795    public void testDoFinalbyteArrayintintbyteArrayint() throws Exception {
796        byte[] b = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
797        byte[] b1 = new byte[30];
798
799        Cipher c = Cipher.getInstance("DES/CBC/NoPadding");
800        c.init(Cipher.ENCRYPT_MODE, cipherKeyDES);
801        try {
802            c.doFinal(b, 0, 10, b1, 5);
803            fail("IllegalBlockSizeException expected");
804        } catch (IllegalBlockSizeException e) {
805            //expected
806        }
807
808        c = Cipher.getInstance("DES/CBC/NoPadding");
809        try {
810            c.doFinal(b, 0, 10, b1, 5);
811            fail("IllegalStateException expected");
812        } catch (IllegalStateException e) {
813            //expected
814        }
815
816        c = Cipher.getInstance("DES/CBC/NoPadding");
817        c.init(Cipher.ENCRYPT_MODE, cipherKeyDES);
818        c.doFinal(b, 0, 16, b1, 0);
819
820        SecureRandom sr = new SecureRandom();
821        byte[] iv = new byte[8];
822        sr.nextBytes(iv);
823        AlgorithmParameterSpec ap = new IvParameterSpec(iv);
824
825        c = Cipher.getInstance("DES/CBC/PKCS5Padding");
826        c.init(Cipher.DECRYPT_MODE, cipherKeyDES, ap);
827
828        try {
829            c.doFinal(b1, 0, 24, new byte[42], 0);
830            fail("BadPaddingException expected");
831        } catch (BadPaddingException e) {
832            //expected
833        }
834
835        b1 = new byte[6];
836        c = Cipher.getInstance("DESede");
837        c.init(Cipher.ENCRYPT_MODE, cipherKey);
838        try {
839            c.doFinal(b, 3, 6, b1, 5);
840            fail("No expected ShortBufferException");
841        } catch (ShortBufferException e) {
842            //expected
843        }
844    }
845
846    @TestTargetNew(
847        level = TestLevel.COMPLETE,
848        notes = "",
849        method = "getMaxAllowedKeyLength",
850        args = {java.lang.String.class}
851    )
852    public void testGetMaxAllowedKeyLength() throws NoSuchAlgorithmException {
853        try {
854            Cipher.getMaxAllowedKeyLength(null);
855            fail("No expected NullPointerException");
856        } catch (NullPointerException e) {
857        }
858        try {
859            Cipher.getMaxAllowedKeyLength("//CBC/PKCS5Paddin");
860            fail("No expected NoSuchAlgorithmException");
861        } catch (NoSuchAlgorithmException e) {
862        }
863        try {
864            Cipher.getMaxAllowedKeyLength("/DES/CBC/PKCS5Paddin/1");
865            fail("No expected NoSuchAlgorithmException");
866        } catch (NoSuchAlgorithmException e) {
867        }
868        assertTrue(Cipher.getMaxAllowedKeyLength("/DES/CBC/PKCS5Paddin") > 0);
869    }
870
871    @TestTargetNew(
872        level = TestLevel.COMPLETE,
873        notes = "",
874        method = "getMaxAllowedParameterSpec",
875        args = {java.lang.String.class}
876    )
877    public void testGetMaxAllowedParameterSpec()
878            throws NoSuchAlgorithmException, Exception {
879        try {
880            Cipher.getMaxAllowedParameterSpec(null);
881            fail("No expected NullPointerException");
882        } catch (NullPointerException e) {
883        }
884        try {
885            Cipher.getMaxAllowedParameterSpec("/DES//PKCS5Paddin");
886            fail("No expected NoSuchAlgorithmException");
887        } catch (NoSuchAlgorithmException e) {
888        }
889        try {
890            Cipher.getMaxAllowedParameterSpec("/DES/CBC/ /1");
891            fail("No expected NoSuchAlgorithmException");
892        } catch (NoSuchAlgorithmException e) {
893        }
894        Cipher.getMaxAllowedParameterSpec("DES/CBC/PKCS5Paddin");
895        Cipher.getMaxAllowedParameterSpec("RSA");
896    }
897
898    /**
899     * @tests javax.crypto.Cipher#Cipher(CipherSpi cipherSpi, Provider provider,
900     *        String transformation)
901     */
902    @TestTargetNew(
903        level = TestLevel.COMPLETE,
904        notes = "",
905        method = "Cipher",
906        args = {javax.crypto.CipherSpi.class, java.security.Provider.class, java.lang.String.class}
907    )
908    public void test_Ctor() throws Exception {
909        // Regression for Harmony-1184
910        try {
911            new testCipher(null, null, "s");
912            fail("NullPointerException expected");
913        } catch (NullPointerException e) {
914            // expected
915        }
916
917        try {
918            new testCipher(new MyCipher(), null, "s");
919            fail("NullPointerException expected for 'null' provider");
920        } catch (NullPointerException e) {
921            // expected
922        }
923
924        try {
925            new testCipher(null, new Provider("qwerty", 1.0, "qwerty") {}, "s");
926            fail("NullPointerException expected for 'null' cipherSpi");
927        } catch (NullPointerException e) {
928            // expected
929        }
930    }
931
932    @TestTargets({
933        @TestTargetNew(
934            level = TestLevel.COMPLETE,
935            notes = "",
936            method = "doFinal",
937            args = {java.nio.ByteBuffer.class, java.nio.ByteBuffer.class}
938        ),
939        @TestTargetNew(
940            level = TestLevel.COMPLETE,
941            notes = "",
942            clazz = CipherSpi.class,
943            method = "engineDoFinal",
944            args = {java.nio.ByteBuffer.class, java.nio.ByteBuffer.class}
945        )
946    })
947    public void test_doFinalLjava_nio_ByteBufferLjava_nio_ByteBuffer ()
948    throws NoSuchAlgorithmException, NoSuchPaddingException,
949    InvalidKeyException, ShortBufferException, BadPaddingException,
950    IllegalBlockSizeException, InvalidAlgorithmParameterException {
951        byte[] b = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
952        ByteBuffer bInput = ByteBuffer.allocate(64);
953        ByteBuffer bOutput = ByteBuffer.allocate(64);
954
955        Cipher c = Cipher.getInstance("DES/CBC/NoPadding");
956        c.init(Cipher.ENCRYPT_MODE, cipherKeyDES);
957        bInput.put(b, 0, 10);
958        try {
959            c.doFinal(bInput, bOutput);
960            fail("IllegalBlockSizeException expected");
961        } catch (IllegalBlockSizeException e) {
962            //expected
963        }
964
965        c = Cipher.getInstance("DES/CBC/NoPadding");
966        try {
967            c.doFinal(bInput, bOutput);
968            fail("IllegalStateException expected");
969        } catch (IllegalStateException e) {
970            //expected
971        }
972
973        c = Cipher.getInstance("DES/CBC/NoPadding");
974        c.init(Cipher.ENCRYPT_MODE, cipherKeyDES);
975        bInput = ByteBuffer.allocate(16);
976        bInput.put(b, 0, 16);
977        c.doFinal(bInput, bOutput);
978
979        SecureRandom sr = new SecureRandom();
980        byte[] iv = new byte[8];
981        sr.nextBytes(iv);
982        AlgorithmParameterSpec ap = new IvParameterSpec(iv);
983
984        c = Cipher.getInstance("DES/CBC/PKCS5Padding");
985        c.init(Cipher.DECRYPT_MODE, cipherKeyDES, ap);
986        bInput = ByteBuffer.allocate(64);
987
988        try {
989            c.doFinal(bOutput, bInput);
990            fail("BadPaddingException expected");
991        } catch (BadPaddingException e) {
992            //expected
993        }
994
995        c = Cipher.getInstance("DES/CBC/NoPadding");
996        c.init(Cipher.ENCRYPT_MODE, cipherKeyDES);
997        bInput.put(b, 0, 16);
998        try {
999            c.doFinal(bInput, bInput);
1000            fail("IllegalArgumentException expected");
1001        } catch (IllegalArgumentException e) {
1002            //expected
1003        }
1004
1005        c = Cipher.getInstance("DES/CBC/NoPadding");
1006        c.init(Cipher.ENCRYPT_MODE, cipherKeyDES);
1007        bInput.put(b, 0, 16);
1008        try {
1009            c.doFinal(bInput, bOutput.asReadOnlyBuffer());
1010            fail("ReadOnlyBufferException expected");
1011        } catch (ReadOnlyBufferException e) {
1012            //expected
1013        }
1014
1015        bInput.rewind();
1016        bInput.put(b, 0, 16);
1017        bOutput = ByteBuffer.allocate(8);
1018        c = Cipher.getInstance("DESede");
1019        c.init(Cipher.ENCRYPT_MODE, cipherKey);
1020        try {
1021            c.doFinal(bInput, bOutput);
1022            fail("No expected ShortBufferException");
1023        } catch (ShortBufferException e) {
1024            //expected
1025        }
1026    }
1027
1028    @TestTargetNew(
1029        level = TestLevel.COMPLETE,
1030        notes = "",
1031        method = "init",
1032        args = {int.class, java.security.Key.class, java.security.AlgorithmParameters.class}
1033    )
1034    public void test_initILjava_security_KeyLjava_security_AlgorithmParameters ()
1035    throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
1036    InvalidAlgorithmParameterException {
1037        SecureRandom sr = new SecureRandom();
1038        byte[] iv = new byte[8];
1039        sr.nextBytes(iv);
1040        AlgorithmParameterSpec ap = new IvParameterSpec(iv);
1041
1042        Cipher c = Cipher.getInstance("DES/CBC/PKCS5Padding");
1043        c.init(Cipher.DECRYPT_MODE, cipherKeyDES, ap);
1044        assertNotNull(c.getParameters());
1045
1046        try {
1047            c.init(Cipher.DECRYPT_MODE, cipherKey, ap);
1048            fail("InvalidKeyException e");
1049        } catch (InvalidKeyException e) {
1050            //expected
1051        }
1052
1053        try {
1054            c.init(Cipher.DECRYPT_MODE, cipherKeyDES, (AlgorithmParameters)null);
1055            fail("InvalidAlgorithmParameterException e");
1056        } catch (InvalidAlgorithmParameterException e) {
1057            //expected
1058        }
1059    }
1060
1061    @TestTargets({
1062        @TestTargetNew(
1063            level = TestLevel.COMPLETE,
1064            notes = "",
1065            method = "init",
1066            args = {int.class, java.security.Key.class, java.security.AlgorithmParameters.class, java.security.SecureRandom.class}
1067        ),
1068        @TestTargetNew(
1069            level = TestLevel.COMPLETE,
1070            notes = "",
1071            clazz = CipherSpi.class,
1072            method = "engineInit",
1073            args = {int.class, java.security.Key.class, java.security.AlgorithmParameters.class, java.security.SecureRandom.class}
1074        )
1075    })
1076    public void test_initILjava_security_KeyLjava_security_AlgorithmParametersLjava_security_SecureRandom ()
1077    throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
1078    InvalidAlgorithmParameterException {
1079        SecureRandom sr = new SecureRandom();
1080        byte[] iv = new byte[8];
1081        sr.nextBytes(iv);
1082        AlgorithmParameterSpec ap = new IvParameterSpec(iv);
1083
1084        Cipher c = Cipher.getInstance("DES/CBC/PKCS5Padding");
1085        c.init(Cipher.DECRYPT_MODE, cipherKeyDES, ap, sr);
1086        assertNotNull(c.getParameters());
1087
1088        try {
1089            c.init(Cipher.DECRYPT_MODE, cipherKey, ap, new SecureRandom());
1090            fail("InvalidKeyException e");
1091        } catch (InvalidKeyException e) {
1092            //expected
1093        }
1094
1095        try {
1096            c.init(Cipher.DECRYPT_MODE, cipherKeyDES, (AlgorithmParameters)null, sr);
1097            fail("InvalidAlgorithmParameterException e");
1098        } catch (InvalidAlgorithmParameterException e) {
1099            //expected
1100        }
1101
1102        c.init(Cipher.DECRYPT_MODE, cipherKeyDES, ap, (SecureRandom)null);
1103        assertNotNull(c.getParameters());
1104    }
1105
1106    @TestTargetNew(
1107        level = TestLevel.COMPLETE,
1108        notes = "",
1109        method = "init",
1110        args = {int.class, java.security.cert.Certificate.class}
1111    )
1112    public void test_initILjava_security_cert_Certificate ()
1113    throws MalformedURLException, IOException, CertificateException,
1114    NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
1115
1116    /* Certificate creation notes: certificate should be valid 37273 starting
1117     * from 13 Nov 2008
1118     * If it brcomes invalidated regenerate it using following commands:
1119     * 1. openssl genrsa -des3 -out test.key 1024
1120     * 2. openssl req -new -key test.key -out test.csr
1121     * 3. cp test.key test.key.org
1122     * 4. openssl rsa -in test.key.org -out test.key
1123     * 5. openssl x509 -req -days 37273 -in test.csr -signkey test.key -out test.cert
1124     * */
1125
1126        String certName = Support_Resources.getURL("test.cert");
1127        InputStream is = new URL(certName).openConnection().getInputStream();
1128        CertificateFactory cf = CertificateFactory.getInstance("X.509");
1129
1130        Certificate cert = cf.generateCertificate(is);
1131
1132        Cipher c = Cipher.getInstance("RSA");
1133
1134        c.init(Cipher.ENCRYPT_MODE, cert);
1135        c = Cipher.getInstance("DES/CBC/PKCS5Padding");
1136        try {
1137            c.init(Cipher.ENCRYPT_MODE, cert);
1138            fail("InvalidKeyException expected");
1139        } catch (InvalidKeyException e) {
1140            //expected
1141        }
1142    }
1143
1144    @TestTargetNew(
1145        level = TestLevel.COMPLETE,
1146        notes = "",
1147        method = "init",
1148        args = {int.class, java.security.cert.Certificate.class, java.security.SecureRandom.class}
1149    )
1150    public void test_initILjava_security_cert_Certificate_java_security_SecureRandom ()
1151    throws MalformedURLException, IOException, CertificateException,
1152    NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
1153
1154    /* Certificate creation notes: certificate should be valid 37273 starting
1155     * from 13 Nov 2008
1156     * If it brcomes invalidated regenerate it using following commands:
1157     * 1. openssl genrsa -des3 -out test.key 1024
1158     * 2. openssl req -new -key test.key -out test.csr
1159     * 3. cp test.key test.key.org
1160     * 4. openssl rsa -in test.key.org -out test.key
1161     * 5. openssl x509 -req -days 37273 -in test.csr -signkey test.key -out test.cert
1162     * */
1163
1164        String certName = Support_Resources.getURL("test.cert");
1165        InputStream is = new URL(certName).openConnection().getInputStream();
1166        CertificateFactory cf = CertificateFactory.getInstance("X.509");
1167
1168        Certificate cert = cf.generateCertificate(is);
1169
1170        Cipher c = Cipher.getInstance("RSA");
1171
1172        c.init(Cipher.ENCRYPT_MODE, cert, new SecureRandom());
1173        c = Cipher.getInstance("DES/CBC/PKCS5Padding");
1174        try {
1175            c.init(Cipher.ENCRYPT_MODE, cert, new SecureRandom());
1176            fail("InvalidKeyException expected");
1177        } catch (InvalidKeyException e) {
1178            //expected
1179        }
1180    }
1181
1182    @TestTargets({
1183        @TestTargetNew(
1184            level = TestLevel.COMPLETE,
1185            notes = "",
1186            method = "unwrap",
1187            args = {byte[].class, java.lang.String.class, int.class}
1188        ),
1189        @TestTargetNew(
1190                level = TestLevel.COMPLETE,
1191                notes = "",
1192                clazz = CipherSpi.class,
1193                method = "engineUnwrap",
1194                args = {byte[].class, java.lang.String.class, int.class}
1195        )
1196    })
1197    public void test_unwrap$BLjava_lang_StringI () throws NoSuchAlgorithmException,
1198    NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException,
1199    IllegalBlockSizeException {
1200        SecureRandom sr = new SecureRandom();
1201        byte[] iv = new byte[8];
1202        sr.nextBytes(iv);
1203        AlgorithmParameterSpec ap = new IvParameterSpec(iv);
1204
1205        Cipher c = Cipher.getInstance("DES/CBC/PKCS5Padding");
1206
1207        c.init(Cipher.WRAP_MODE, cipherKeyDES, ap, sr);
1208        byte[] arDES = c.wrap(cipherKeyDES);
1209        byte[] ar    = c.wrap(cipherKey);
1210
1211        try {
1212            c.unwrap(arDES, "DES", Cipher.SECRET_KEY);
1213            fail("IllegalStateException expected");
1214        } catch (IllegalStateException e) {
1215            //expected
1216        }
1217
1218        c.init(Cipher.UNWRAP_MODE, cipherKeyDES, ap, sr);
1219        assertTrue(cipherKeyDES.equals(c.unwrap(arDES, "DES", Cipher.SECRET_KEY)));
1220        assertFalse(cipherKeyDES.equals(c.unwrap(ar, "DES", Cipher.SECRET_KEY)));
1221
1222        try {
1223            c.unwrap(arDES, "RSA38", Cipher.PUBLIC_KEY);
1224            fail("NoSuchAlgorithmException expected");
1225        } catch (NoSuchAlgorithmException e) {
1226            //expected
1227        }
1228
1229        c = Cipher.getInstance("DESede/CBC/PKCS5Padding");
1230        c.init(Cipher.UNWRAP_MODE, cipherKey, ap, sr);
1231        try {
1232            c.unwrap(arDES, "DESede", Cipher.SECRET_KEY);
1233            fail("InvalidKeyException expected");
1234        } catch (InvalidKeyException e) {
1235            //expected
1236        }
1237    }
1238
1239    @TestTargets({
1240        @TestTargetNew(
1241            level = TestLevel.COMPLETE,
1242            notes = "",
1243            method = "update",
1244            args = {java.nio.ByteBuffer.class, java.nio.ByteBuffer.class}
1245        ),
1246        @TestTargetNew(
1247                level = TestLevel.COMPLETE,
1248                notes = "",
1249                clazz = CipherSpi.class,
1250                method = "engineUpdate",
1251                args = {java.nio.ByteBuffer.class, java.nio.ByteBuffer.class}
1252        )
1253    })
1254    public void test_updateLjava_nio_ByteBufferLjava_nio_ByteBuffer () throws
1255    NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
1256    ShortBufferException, InvalidAlgorithmParameterException {
1257        byte[] b = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
1258        ByteBuffer bInput = ByteBuffer.allocate(256);
1259        ByteBuffer bOutput = ByteBuffer.allocate(256);
1260
1261        Cipher c = Cipher.getInstance("DES/CBC/NoPadding");
1262        c.init(Cipher.ENCRYPT_MODE, cipherKeyDES);
1263        bInput.put(b, 0, 10);
1264        bInput.rewind();
1265        bOutput.rewind();
1266        c.update(bInput, bOutput);
1267
1268        c = Cipher.getInstance("DES/CBC/NoPadding");
1269        try {
1270            c.update(bInput, bOutput);
1271            fail("IllegalStateException expected");
1272        } catch (IllegalStateException e) {
1273            //expected
1274        }
1275
1276        c = Cipher.getInstance("DES/CBC/NoPadding");
1277        c.init(Cipher.ENCRYPT_MODE, cipherKeyDES);
1278        bInput = ByteBuffer.allocate(16);
1279        bInput.put(b, 0, 16);
1280        bInput.rewind();
1281        bOutput.rewind();
1282        c.update(bInput, bOutput);
1283
1284        SecureRandom sr = new SecureRandom();
1285        byte[] iv = new byte[8];
1286        sr.nextBytes(iv);
1287        AlgorithmParameterSpec ap = new IvParameterSpec(iv);
1288
1289        c = Cipher.getInstance("DES/CBC/PKCS5Padding");
1290        c.init(Cipher.DECRYPT_MODE, cipherKeyDES, ap);
1291        bInput = ByteBuffer.allocate(64);
1292
1293        c = Cipher.getInstance("DES/CBC/NoPadding");
1294        c.init(Cipher.ENCRYPT_MODE, cipherKeyDES);
1295        bInput.put(b, 0, 16);
1296        bInput.rewind();
1297        try {
1298            c.update(bInput, bInput);
1299            fail("IllegalArgumentException expected");
1300        } catch (IllegalArgumentException e) {
1301            //expected
1302        }
1303
1304        c = Cipher.getInstance("DES/CBC/NoPadding");
1305        c.init(Cipher.ENCRYPT_MODE, cipherKeyDES);
1306        bInput.put(b, 0, 16);
1307        bInput.rewind();
1308        bOutput.rewind();
1309        try {
1310            c.update(bInput, bOutput.asReadOnlyBuffer());
1311            fail("ReadOnlyBufferException expected");
1312        } catch (ReadOnlyBufferException e) {
1313            //expected
1314        }
1315
1316        bInput.rewind();
1317        bInput.put(b, 0, 16);
1318        bInput.rewind();
1319        bOutput = ByteBuffer.allocate(8);
1320        c = Cipher.getInstance("DESede");
1321        c.init(Cipher.ENCRYPT_MODE, cipherKey);
1322        try {
1323            c.update(bInput, bOutput);
1324            fail("No expected ShortBufferException");
1325        } catch (ShortBufferException e) {
1326            //expected
1327        }
1328    }
1329
1330    class Mock_Key implements Key {
1331        public String getAlgorithm() {
1332            return null;
1333        }
1334
1335        public byte[] getEncoded() {
1336            return null;
1337        }
1338
1339        public String getFormat() {
1340            return null;
1341        }
1342
1343    }
1344
1345    @TestTargets({
1346        @TestTargetNew(
1347            level = TestLevel.COMPLETE,
1348            notes = "",
1349            method = "wrap",
1350            args = {java.security.Key.class}
1351        ),
1352        @TestTargetNew(
1353                level = TestLevel.COMPLETE,
1354                notes = "",
1355                clazz = CipherSpi.class,
1356                method = "engineWrap",
1357                args = {java.security.Key.class}
1358        )
1359    })
1360    public void test_wrap_java_security_Key () throws NoSuchAlgorithmException,
1361    NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException,
1362    InvalidAlgorithmParameterException, MalformedURLException, IOException,
1363    CertificateException {
1364        SecureRandom sr = new SecureRandom();
1365        byte[] iv = new byte[8];
1366        sr.nextBytes(iv);
1367        AlgorithmParameterSpec ap = new IvParameterSpec(iv);
1368
1369        Cipher c = Cipher.getInstance("DES/CBC/PKCS5Padding");
1370
1371        c.init(Cipher.WRAP_MODE, cipherKeyDES, ap, sr);
1372        assertNotNull(c.wrap(cipherKeyDES));
1373        assertNotNull(c.wrap(cipherKey));
1374        String certName = Support_Resources.getURL("test.cert");
1375        InputStream is = new URL(certName).openConnection().getInputStream();
1376        CertificateFactory cf = CertificateFactory.getInstance("X.509");
1377
1378        Certificate cert = cf.generateCertificate(is);
1379        assertNotNull(c.wrap(cert.getPublicKey()));
1380
1381        c = Cipher.getInstance("DES/CBC/NoPadding");
1382        c.init(Cipher.WRAP_MODE, cipherKeyDES, ap, sr);
1383        try {
1384            assertNotNull(c.wrap(cert.getPublicKey()));
1385            fail("IllegalBlockSizeException expected");
1386        } catch (IllegalBlockSizeException e) {
1387            //expected
1388        }
1389
1390        c.init(Cipher.DECRYPT_MODE, cipherKeyDES, ap, sr);
1391
1392        try {
1393            c.wrap(cipherKeyDES);
1394            fail("IllegalStateException expected");
1395        } catch (IllegalStateException e) {
1396            //expected
1397        }
1398
1399        c.init(Cipher.WRAP_MODE, cipherKeyDES, ap, sr);
1400        try {
1401            c.wrap(new Mock_Key());
1402            fail("InvalidKeyException expected");
1403        } catch (InvalidKeyException e) {
1404            //expected
1405        }
1406    }
1407
1408    @TestTargetNew(
1409        level = TestLevel.COMPLETE,
1410        notes = "",
1411        method = "doFinal",
1412        args = {byte[].class, int.class}
1413    )
1414    public void test_doFinal$BI() throws Exception {
1415        byte[] b = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
1416        byte[] b1 = new byte[30];
1417
1418        Cipher c = Cipher.getInstance("DES/CBC/NoPadding");
1419        c.init(Cipher.ENCRYPT_MODE, cipherKeyDES);
1420        c.update(b, 0, 10);
1421        try {
1422            c.doFinal(b1, 5);
1423            fail("IllegalBlockSizeException expected");
1424        } catch (IllegalBlockSizeException e) {
1425            //expected
1426        }
1427
1428        c = Cipher.getInstance("DES/CBC/NoPadding");
1429        try {
1430            c.doFinal(b1, 5);
1431            fail("IllegalStateException expected");
1432        } catch (IllegalStateException e) {
1433            //expected
1434        }
1435
1436        c = Cipher.getInstance("DES/CBC/NoPadding");
1437        c.init(Cipher.ENCRYPT_MODE, cipherKeyDES);
1438        c.update(b, 3, 8);
1439        c.doFinal(b1, 0);
1440
1441        SecureRandom sr = new SecureRandom();
1442        byte[] iv = new byte[8];
1443        sr.nextBytes(iv);
1444        AlgorithmParameterSpec ap = new IvParameterSpec(iv);
1445
1446        c = Cipher.getInstance("DES/CBC/PKCS5Padding");
1447        c.init(Cipher.DECRYPT_MODE, cipherKeyDES, ap);
1448
1449        c.update(b1, 0, 24);
1450        try {
1451            c.doFinal(b, 0);
1452            fail("BadPaddingException expected");
1453        } catch (BadPaddingException e) {
1454            //expected
1455        }
1456
1457        b1 = new byte[6];
1458        c = Cipher.getInstance("DESede");
1459        c.init(Cipher.ENCRYPT_MODE, cipherKey);
1460        c.update(b, 3, 6);
1461        try {
1462            c.doFinal(b1, 5);
1463            fail("No expected ShortBufferException");
1464        } catch (ShortBufferException e) {
1465            //expected
1466        }
1467    }
1468
1469    @TestTargetNew(
1470        level = TestLevel.COMPLETE,
1471        notes = "",
1472        method = "doFinal",
1473        args = {byte[].class}
1474    )
1475    public void test_doFinal$B() throws Exception {
1476        byte[] b1 = new byte[32];
1477        byte[] bI1 = {1,2,3,4,5,6,7,8,9,10};
1478        byte[] bI2 = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
1479        byte[] bI3 = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
1480        byte[] bI4 = {1,2,3};
1481
1482        Cipher c = Cipher.getInstance("DES/CBC/NoPadding");
1483        c.init(Cipher.ENCRYPT_MODE, cipherKeyDES);
1484        try {
1485            c.doFinal(bI1);
1486            fail("IllegalBlockSizeException expected");
1487        } catch (IllegalBlockSizeException e) {
1488            //expected
1489        }
1490
1491        c = Cipher.getInstance("DES/CBC/NoPadding");
1492        try {
1493            c.doFinal(bI1);
1494            fail("IllegalStateException expected");
1495        } catch (IllegalStateException e) {
1496            //expected
1497        }
1498
1499        c = Cipher.getInstance("DES/CBC/NoPadding");
1500        c.init(Cipher.ENCRYPT_MODE, cipherKeyDES);
1501        c.doFinal(bI2);
1502        c.init(Cipher.ENCRYPT_MODE, cipherKeyDES);
1503        c.doFinal(bI3, 0, 16, b1, 0);
1504
1505        SecureRandom sr = new SecureRandom();
1506        byte[] iv = new byte[8];
1507        sr.nextBytes(iv);
1508        AlgorithmParameterSpec ap = new IvParameterSpec(iv);
1509
1510        c = Cipher.getInstance("DES/CBC/PKCS5Padding");
1511        c.init(Cipher.DECRYPT_MODE, cipherKeyDES, ap);
1512
1513        try {
1514            c.doFinal(b1);
1515            fail("BadPaddingException expected");
1516        } catch (BadPaddingException e) {
1517            //expected
1518        }
1519    }
1520
1521    @TestTargets({
1522        @TestTargetNew(
1523            level = TestLevel.COMPLETE,
1524            notes = "",
1525            method = "doFinal",
1526            args = {byte[].class, int.class, int.class}
1527        ),
1528        @TestTargetNew(
1529            level = TestLevel.COMPLETE,
1530            notes = "",
1531            clazz = CipherSpi.class,
1532            method = "engineDoFinal",
1533            args = {byte[].class, int.class, int.class}
1534        )
1535    })
1536    public void test_doFinal$BII() throws Exception {
1537        byte[] b = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
1538        byte[] b1 = new byte[30];
1539
1540        Cipher c = Cipher.getInstance("DES/CBC/NoPadding");
1541        c.init(Cipher.ENCRYPT_MODE, cipherKeyDES);
1542        try {
1543            c.doFinal(b, 0, 10);
1544            fail("IllegalBlockSizeException expected");
1545        } catch (IllegalBlockSizeException e) {
1546            //expected
1547        }
1548
1549        c = Cipher.getInstance("DES/CBC/NoPadding");
1550        try {
1551            c.doFinal(b, 0, 10);
1552            fail("IllegalStateException expected");
1553        } catch (IllegalStateException e) {
1554            //expected
1555        }
1556
1557        c = Cipher.getInstance("DES/CBC/NoPadding");
1558        c.init(Cipher.ENCRYPT_MODE, cipherKeyDES);
1559        c.doFinal(b, 0, 16);
1560        c.init(Cipher.ENCRYPT_MODE, cipherKeyDES);
1561        c.doFinal(b, 0, 16, b1, 0);
1562
1563        SecureRandom sr = new SecureRandom();
1564        byte[] iv = new byte[8];
1565        sr.nextBytes(iv);
1566        AlgorithmParameterSpec ap = new IvParameterSpec(iv);
1567
1568        c = Cipher.getInstance("DES/CBC/PKCS5Padding");
1569        c.init(Cipher.DECRYPT_MODE, cipherKeyDES, ap);
1570
1571        try {
1572            c.doFinal(b1, 0, 24);
1573            fail("BadPaddingException expected");
1574        } catch (BadPaddingException e) {
1575            //expected
1576        }
1577    }
1578
1579    @TestTargetNew(
1580        level = TestLevel.COMPLETE,
1581        notes = "",
1582        method = "doFinal",
1583        args = {byte[].class, int.class, int.class, byte[].class}
1584    )
1585    public void test_doFinal$BII$B() throws Exception {
1586        byte[] b = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
1587        byte[] b1 = new byte[30];
1588
1589        Cipher c = Cipher.getInstance("DES/CBC/NoPadding");
1590        c.init(Cipher.ENCRYPT_MODE, cipherKeyDES);
1591        try {
1592            c.doFinal(b, 0, 10, b1);
1593            fail("IllegalBlockSizeException expected");
1594        } catch (IllegalBlockSizeException e) {
1595            //expected
1596        }
1597
1598        c = Cipher.getInstance("DES/CBC/NoPadding");
1599        try {
1600            c.doFinal(b, 0, 10, b1);
1601            fail("IllegalStateException expected");
1602        } catch (IllegalStateException e) {
1603            //expected
1604        }
1605
1606        c = Cipher.getInstance("DES/CBC/NoPadding");
1607        c.init(Cipher.ENCRYPT_MODE, cipherKeyDES);
1608        c.doFinal(b, 0, 16, b1);
1609
1610        SecureRandom sr = new SecureRandom();
1611        byte[] iv = new byte[8];
1612        sr.nextBytes(iv);
1613        AlgorithmParameterSpec ap = new IvParameterSpec(iv);
1614
1615        c = Cipher.getInstance("DES/CBC/PKCS5Padding");
1616        c.init(Cipher.DECRYPT_MODE, cipherKeyDES, ap);
1617
1618        try {
1619            c.doFinal(b1, 0, 24, new byte[42]);
1620            fail("BadPaddingException expected");
1621        } catch (BadPaddingException e) {
1622            //expected
1623        }
1624
1625        b1 = new byte[6];
1626        c = Cipher.getInstance("DESede");
1627        c.init(Cipher.ENCRYPT_MODE, cipherKey);
1628        try {
1629            c.doFinal(b, 3, 6, b1);
1630            fail("No expected ShortBufferException");
1631        } catch (ShortBufferException e) {
1632            //expected
1633        }
1634    }
1635
1636    @TestTargetNew(
1637        level = TestLevel.PARTIAL_COMPLETE,
1638        notes = "Checks exception",
1639        method = "update",
1640        args = {byte[].class}
1641    )
1642    public void test_update$B() throws Exception {
1643        Cipher cipher = Cipher.getInstance("DESEDE/CBC/PKCS5Padding");
1644        try {
1645            cipher.update(new byte[64]);
1646            fail("IllegalStateException expected");
1647        } catch (IllegalStateException e) {
1648            //expected
1649        }
1650    }
1651
1652    @TestTargetNew(
1653        level = TestLevel.COMPLETE,
1654        notes = "",
1655        method = "update",
1656        args = {byte[].class, int.class, int.class, byte[].class}
1657    )
1658    public void test_() throws Exception {
1659        byte[] b = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
1660        byte[] b1 = new byte[30];
1661
1662        Cipher c = Cipher.getInstance("DES/CBC/NoPadding");
1663
1664        try {
1665            c.update(b, 0, 10, b1);
1666            fail("IllegalStateException expected");
1667        } catch (IllegalStateException e) {
1668            //expected
1669        }
1670
1671        c = Cipher.getInstance("DES/CBC/NoPadding");
1672        c.init(Cipher.ENCRYPT_MODE, cipherKeyDES);
1673        c.update(b, 0, 16, b1);
1674
1675        b1 = new byte[3];
1676
1677        try {
1678            c.update(b, 3, 15, b1);
1679            fail("No expected ShortBufferException");
1680        } catch (ShortBufferException e) {
1681            //expected
1682        }
1683    }
1684
1685    class testCipher extends Cipher {
1686        testCipher(CipherSpi c, Provider p, String s) {
1687            super(c, p, s);
1688        }
1689    }
1690}
1691