1 /*
   2  * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 import java.security.InvalidAlgorithmParameterException;
  25 import java.security.InvalidKeyException;
  26 import java.security.NoSuchAlgorithmException;
  27 import java.security.NoSuchProviderException;
  28 import java.security.spec.AlgorithmParameterSpec;
  29 import java.util.Random;
  30 import javax.crypto.BadPaddingException;
  31 import javax.crypto.Cipher;
  32 import javax.crypto.IllegalBlockSizeException;
  33 import javax.crypto.KeyGenerator;
  34 import javax.crypto.NoSuchPaddingException;
  35 import javax.crypto.SecretKey;
  36 import javax.crypto.ShortBufferException;
  37 import javax.crypto.spec.IvParameterSpec;
  38 
  39 /**
  40  * @test
  41  * @bug 8043836
  42  * @summary Test AES ciphers with different modes and padding schemes (ECB mode
  43  *          doesn't use IV).
  44  * @author Liwen Wang
  45  * @author Parag Salvi
  46  * @key randomness
  47  */
  48 public class TestAESCipher {
  49 
  50     private static final String ALGORITHM = "AES";
  51     private static final String PROVIDER = "SunJCE";
  52     private static final String[] MODES = { "ECb", "CbC", "CTR", "PCBC", "OFB",
  53         "OFB150", "cFB", "CFB7", "cFB8", "cFB16", "cFB24", "cFB32",
  54         "Cfb40", "cfB48", "cfB56", "cfB64", "cfB72", "cfB80", "cfB88",
  55         "cfB96", "cfb104", "cfB112", "cfB120", "OFB8", "OFB16", "OFB24",
  56         "OFB32", "OFB40", "OFB48", "OFB56", "OFB64", "OFB72", "OFB80",
  57         "OFB88", "OFB96", "OFB104", "OFB112", "OFB120", "GCM" };
  58     private static final String[] PADDING = { "NoPadding", "PKCS5Padding" };
  59     private static final int KEY_LENGTH = 128;
  60 
  61     public static void main(String argv[]) throws Exception {
  62         TestAESCipher test = new TestAESCipher();
  63         for (String mode : MODES) {
  64             int padKinds = 1;
  65             if (mode.equalsIgnoreCase("ECB") || mode.equalsIgnoreCase("PCBC")
  66                     || mode.equalsIgnoreCase("CBC")) {
  67                 padKinds = PADDING.length;
  68             }
  69 
  70             for (int k = 0; k < padKinds; k++) {
  71                 test.runTest(ALGORITHM, mode, PADDING[k]);
  72             }
  73         }
  74     }
  75 
  76     public void runTest(String algo, String mo, String pad) throws Exception {
  77         Cipher ci = null;
  78         byte[] iv = null;
  79         AlgorithmParameterSpec aps = null;
  80         SecretKey key = null;
  81         try {
  82             // Initialization
  83             Random rdm = new Random();
  84             byte[] plainText = new byte[128];
  85             rdm.nextBytes(plainText);
  86 
  87             ci = Cipher.getInstance(algo + "/" + mo + "/" + pad, PROVIDER);
  88             KeyGenerator kg = KeyGenerator.getInstance(algo, PROVIDER);
  89             kg.init(KEY_LENGTH);
  90             key = kg.generateKey();
  91 
  92             // encrypt
  93             if (!mo.equalsIgnoreCase("GCM")) {
  94                 ci.init(Cipher.ENCRYPT_MODE, key, aps);
  95             } else {
  96                 ci.init(Cipher.ENCRYPT_MODE, key);
  97             }
  98 
  99             byte[] cipherText = new byte[ci.getOutputSize(plainText.length)];
 100             int offset = ci.update(plainText, 0, plainText.length, cipherText,
 101                     0);
 102             ci.doFinal(cipherText, offset);
 103 
 104             if (!mo.equalsIgnoreCase("ECB")) {
 105                 iv = ci.getIV();
 106                 aps = new IvParameterSpec(iv);
 107             } else {
 108                 aps = null;
 109             }
 110 
 111             if (!mo.equalsIgnoreCase("GCM")) {
 112                 ci.init(Cipher.DECRYPT_MODE, key, aps);
 113             } else {
 114                 ci.init(Cipher.DECRYPT_MODE, key, ci.getParameters());
 115             }
 116 
 117             byte[] recoveredText = new byte[ci.getOutputSize(cipherText.length)];
 118             int len = ci.doFinal(cipherText, 0, cipherText.length,
 119                     recoveredText);
 120             byte[] tmp = new byte[len];
 121             System.arraycopy(recoveredText, 0, tmp, 0, len);
 122 
 123             // Comparison
 124             if (!java.util.Arrays.equals(plainText, tmp)) {
 125                 System.out.println("Original: ");
 126                 dumpBytes(plainText);
 127                 System.out.println("Recovered: ");
 128                 dumpBytes(tmp);
 129                 throw new RuntimeException(
 130                         "Original text is not equal with recovered text, with mode:"
 131                                 + mo);
 132             }
 133 
 134         } catch (NoSuchAlgorithmException e) {
 135             //CFB7 and OFB150 are for negative testing
 136             if (!mo.equalsIgnoreCase("CFB7") && !mo.equalsIgnoreCase("OFB150")) {
 137                 System.out.println("Unexpected NoSuchAlgorithmException with mode: "
 138                         + mo);
 139                 throw new RuntimeException("Test failed!");
 140             }
 141         }  catch ( NoSuchProviderException | NoSuchPaddingException
 142                 | InvalidKeyException | InvalidAlgorithmParameterException
 143                 | ShortBufferException | IllegalBlockSizeException
 144                 | BadPaddingException e) {
 145             System.out.println("Test failed!");
 146             throw e;
 147         }
 148     }
 149 
 150     private void dumpBytes(byte[] bytes) {
 151         for (byte b : bytes) {
 152             System.out.print(Integer.toHexString(b));
 153         }
 154 
 155         System.out.println();
 156     }
 157 }