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 /*
  25  * @test
  26  * @bug 7088989 8014374
  27  * @summary Ensure the AES ciphers of OracleUcrypto provider works correctly
  28  * @key randomness
  29  */
  30 
  31 import java.io.*;
  32 import java.security.*;
  33 import java.security.spec.*;
  34 import java.util.*;
  35 import javax.crypto.*;
  36 import javax.crypto.spec.*;
  37 
  38 public class TestAES extends UcryptoTest {
  39 
  40     private static final String[] PADDEDCIPHER_ALGOS = {
  41         "AES/ECB/PKCS5Padding",
  42         "AES/CBC/PKCS5Padding",
  43         "AES/CFB128/PKCS5Padding"
  44     };
  45 
  46     private static final String[] CIPHER_ALGOS = {
  47         "AES/ECB/NoPadding",
  48         "AES/CBC/NoPadding",
  49         "AES/CFB128/NoPadding",
  50         "AES/CTR/NoPadding",
  51     };
  52 
  53     private static final SecretKey CIPHER_KEY =
  54         new SecretKeySpec(new byte[16], "AES");
  55 
  56     public static void main(String[] args) throws Exception {
  57         main(new TestAES(), null);
  58     }
  59 
  60     public void doTest(Provider prov) throws Exception {
  61         // Provider for testing Interoperability
  62         Provider sunJCEProv = Security.getProvider("SunJCE");
  63 
  64         testCipherInterop(CIPHER_ALGOS, CIPHER_KEY, prov, sunJCEProv);
  65         testCipherInterop(PADDEDCIPHER_ALGOS, CIPHER_KEY, prov, sunJCEProv);
  66 
  67         testCipherOffset(CIPHER_ALGOS, CIPHER_KEY, prov);
  68         testCipherOffset(PADDEDCIPHER_ALGOS, CIPHER_KEY, prov);
  69 
  70         testCipherKeyWrapping(PADDEDCIPHER_ALGOS, CIPHER_KEY, prov, sunJCEProv);
  71         testCipherGCM(CIPHER_KEY, prov);
  72     }
  73 
  74     private static void testCipherInterop(String[] algos, SecretKey key,
  75                                           Provider p,
  76                                           Provider interopP) {
  77         boolean testPassed = true;
  78         byte[] in = new byte[32];
  79         (new SecureRandom()).nextBytes(in);
  80 
  81         for (String algo : algos) {
  82             try {
  83                 // check ENC
  84                 Cipher c;
  85                 try {
  86                     c = Cipher.getInstance(algo, p);
  87                 } catch (NoSuchAlgorithmException nsae) {
  88                     System.out.println("Skipping Unsupported CIP algo: " + algo);
  89                     continue;
  90                 }
  91                 c.init(Cipher.ENCRYPT_MODE, key, (AlgorithmParameters)null, null);
  92                 byte[] eout = c.doFinal(in, 0, in.length);
  93 
  94                 AlgorithmParameters params = c.getParameters();
  95                 Cipher c2 = Cipher.getInstance(algo, interopP);
  96                 c2.init(Cipher.ENCRYPT_MODE, key, params, null);
  97                 byte[] eout2 = c2.doFinal(in, 0, in.length);
  98 
  99                 if (!Arrays.equals(eout, eout2)) {
 100                     System.out.println(algo + ": DIFF FAILED");
 101                     testPassed = false;
 102                 } else {
 103                     System.out.println(algo + ": ENC Passed");
 104                 }
 105 
 106                 // check DEC
 107                 c.init(Cipher.DECRYPT_MODE, key, params, null);
 108                 byte[] dout = c.doFinal(eout);
 109                 c2.init(Cipher.DECRYPT_MODE, key, params, null);
 110                 byte[] dout2 = c2.doFinal(eout2);
 111 
 112                 if (!Arrays.equals(dout, dout2)) {
 113                     System.out.println(algo + ": DIFF FAILED");
 114                     testPassed = false;
 115                 } else {
 116                     System.out.println(algo + ": DEC Passed");
 117                 }
 118             } catch(Exception ex) {
 119                 System.out.println("Unexpected Exception: " + algo);
 120                 ex.printStackTrace();
 121                 testPassed = false;
 122             }
 123         }
 124 
 125         if (!testPassed) {
 126             throw new RuntimeException("One or more CIPHER test failed!");
 127         } else {
 128             System.out.println("CIPHER Interop Tests Passed");
 129         }
 130     }
 131 
 132     private static void testCipherOffset(String[] algos, SecretKey key,
 133                                          Provider p) {
 134         boolean testPassed = true;
 135         byte[] in = new byte[16];
 136         (new SecureRandom()).nextBytes(in);
 137         int blockSize = 16;
 138 
 139         for (int j = 1; j < (in.length - 1); j++) {
 140             System.out.println("Input offset size: " + j);
 141             for (int i = 0; i < algos.length; i++) {
 142                 try {
 143                     // check ENC
 144                     Cipher c;
 145                     try {
 146                         c = Cipher.getInstance(algos[i], p);
 147                     } catch (NoSuchAlgorithmException nsae) {
 148                         System.out.println("Skip Unsupported CIP algo: " + algos[i]);
 149                         continue;
 150                     }
 151                     c.init(Cipher.ENCRYPT_MODE, key, (AlgorithmParameters)null, null);
 152                     byte[] eout = new byte[c.getOutputSize(in.length)];
 153                     int firstPartLen = in.length - j - 1;
 154                     //System.out.print("1st UPDATE: " + firstPartLen);
 155                     int k = c.update(in, 0, firstPartLen, eout, 0);
 156                     k += c.update(in, firstPartLen, 1, eout, k);
 157                     k += c.doFinal(in, firstPartLen+1, j, eout, k);
 158 
 159                     AlgorithmParameters params = c.getParameters();
 160 
 161                     Cipher c2 = Cipher.getInstance(algos[i], p);
 162                     c2.init(Cipher.ENCRYPT_MODE, key, params, null);
 163                     byte[] eout2 = new byte[c2.getOutputSize(in.length)];
 164                     int k2 = c2.update(in, 0, j, eout2, 0);
 165                     k2 += c2.update(in, j, 1, eout2, k2);
 166                     k2 += c2.doFinal(in, j+1, firstPartLen, eout2, k2);
 167 
 168                     if (!checkArrays(eout, k, eout2, k2)) testPassed = false;
 169 
 170                     // check DEC
 171                     c.init(Cipher.DECRYPT_MODE, key, params, null);
 172                     byte[] dout = new byte[c.getOutputSize(eout.length)];
 173                     k = c.update(eout, 0, firstPartLen, dout, 0);
 174                     k += c.update(eout, firstPartLen, 1, dout, k);
 175                     k += c.doFinal(eout, firstPartLen+1, eout.length - firstPartLen - 1, dout, k);
 176                     if (!checkArrays(in, in.length, dout, k)) testPassed = false;
 177                 } catch(Exception ex) {
 178                     System.out.println("Unexpected Exception: " + algos[i]);
 179                     ex.printStackTrace();
 180                     testPassed = false;
 181                 }
 182             }
 183         }
 184         if (!testPassed) {
 185             throw new RuntimeException("One or more CIPHER test failed!");
 186         } else {
 187             System.out.println("CIPHER Offset Tests Passed");
 188         }
 189     }
 190 
 191     private static void testCipherKeyWrapping(String[] algos, SecretKey key,
 192                                               Provider p, Provider interopP)
 193         throws NoSuchAlgorithmException {
 194         boolean testPassed = true;
 195 
 196         // Test SecretKey, PrivateKey and PublicKey
 197         Key[] tbwKeys = new Key[3];
 198         int[] tbwKeyTypes = { Cipher.SECRET_KEY, Cipher.PRIVATE_KEY, Cipher.PUBLIC_KEY };
 199         tbwKeys[0] = new SecretKeySpec(new byte[20], "Blowfish");
 200         KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
 201         kpg.initialize(1024);
 202         KeyPair kp = kpg.generateKeyPair();
 203         tbwKeys[1] = kp.getPrivate();
 204         tbwKeys[2] = kp.getPublic();
 205 
 206         for (int i = 0; i < algos.length; i++) {
 207             try {
 208                 System.out.println(algos[i] + " - Native WRAP/Java UNWRAP");
 209 
 210                 Cipher c1;
 211                 try {
 212                     c1 = Cipher.getInstance(algos[i], p);
 213                 } catch (NoSuchAlgorithmException nsae) {
 214                     System.out.println("Skipping Unsupported CIP algo: " + algos[i]);
 215                     continue;
 216                 }
 217                 c1.init(Cipher.WRAP_MODE, key, (AlgorithmParameters)null, null);
 218                 AlgorithmParameters params = c1.getParameters();
 219                 Cipher c2 = Cipher.getInstance(algos[i], interopP);
 220                 c2.init(Cipher.UNWRAP_MODE, key, params, null);
 221 
 222                 for (int j = 0; j < tbwKeys.length ; j++) {
 223                     byte[] wrappedKey = c1.wrap(tbwKeys[j]);
 224                     Key recovered = c2.unwrap(wrappedKey,
 225                                               tbwKeys[j].getAlgorithm(), tbwKeyTypes[j]);
 226                     if (!checkKeys(tbwKeys[j], recovered)) testPassed = false;
 227                 }
 228 
 229                 System.out.println(algos[i] + " - Java WRAP/Native UNWRAP");
 230                 c1 = Cipher.getInstance(algos[i], interopP);
 231                 c1.init(Cipher.WRAP_MODE, key, (AlgorithmParameters)null, null);
 232                 params = c1.getParameters();
 233                 c2 = Cipher.getInstance(algos[i], p);
 234                 c2.init(Cipher.UNWRAP_MODE, key, params, null);
 235 
 236                 for (int j = 0; j < tbwKeys.length ; j++) {
 237                     byte[] wrappedKey = c1.wrap(tbwKeys[j]);
 238                     Key recovered = c2.unwrap(wrappedKey,
 239                                               tbwKeys[j].getAlgorithm(), tbwKeyTypes[j]);
 240                     if (!checkKeys(tbwKeys[j], recovered)) testPassed = false;
 241                 }
 242 
 243             } catch(Exception ex) {
 244                 System.out.println("Unexpected Exception: " + algos[i]);
 245                 ex.printStackTrace();
 246                 testPassed = false;
 247             }
 248         }
 249         if (!testPassed) {
 250             throw new RuntimeException("One or more CIPHER test failed!");
 251         } else {
 252             System.out.println("CIPHER KeyWrapping Tests Passed");
 253         }
 254     }
 255 
 256 
 257     private static void testCipherGCM(SecretKey key,
 258                                       Provider p) {
 259         boolean testPassed = true;
 260         byte[] in = new byte[16];
 261         (new SecureRandom()).nextBytes(in);
 262 
 263         byte[] iv = new byte[16];
 264         (new SecureRandom()).nextBytes(iv);
 265 
 266 
 267         String algo = "AES/GCM/NoPadding";
 268         int tagLen[] = { 128, 120, 112, 104, 96, 64, 32 };
 269 
 270         try {
 271             Cipher c;
 272             try {
 273                 c = Cipher.getInstance(algo, p);
 274             } catch (NoSuchAlgorithmException nsae) {
 275                 System.out.println("Skipping Unsupported CIP algo: " + algo);
 276                 return;
 277             }
 278             for (int i = 0; i < tagLen.length; i++) {
 279                 // change iv value to pass the key+iv uniqueness cehck for
 280                 // GCM encryption
 281                 iv[0] += 1;
 282                 AlgorithmParameterSpec paramSpec = new GCMParameterSpec(tagLen[i], iv);
 283                 // check ENC
 284                 c.init(Cipher.ENCRYPT_MODE, key, paramSpec, null);
 285                 c.updateAAD(iv);
 286                 byte[] eout = c.doFinal(in, 0, in.length);
 287 
 288                 AlgorithmParameters param = c.getParameters();
 289                 // check DEC
 290                 c.init(Cipher.DECRYPT_MODE, key, param, null);
 291                 c.updateAAD(iv);
 292                 byte[] dout = c.doFinal(eout, 0, eout.length);
 293 
 294                 if (!Arrays.equals(dout, in)) {
 295                     System.out.println(algo + ": PT and RT DIFF FAILED");
 296                     testPassed = false;
 297                 } else {
 298                     System.out.println(algo + ": tagLen " + tagLen[i] + " done");
 299                 }
 300             }
 301         } catch(Exception ex) {
 302             System.out.println("Unexpected Exception: " + algo);
 303             ex.printStackTrace();
 304             testPassed = false;
 305         }
 306         if (!testPassed) {
 307             throw new RuntimeException("One or more CIPHER test failed!");
 308         } else {
 309             System.out.println("CIPHER GCM Tests Passed");
 310         }
 311     }
 312 
 313     private static boolean checkArrays(byte[] a1, int a1Len, byte[] a2, int a2Len) {
 314         boolean equal = true;
 315         if (a1Len != a2Len) {
 316             System.out.println("DIFFERENT OUT LENGTH");
 317             equal = false;
 318         } else {
 319             for (int p = 0; p < a1Len; p++) {
 320                 if (a1[p] != a2[p]) {
 321                     System.out.println("DIFF FAILED");
 322                     equal = false;
 323                     break;
 324                 }
 325             }
 326         }
 327         return equal;
 328     }
 329 
 330     private static boolean checkKeys(Key k1, Key k2) {
 331         boolean equal = true;
 332         if (!k1.getAlgorithm().equalsIgnoreCase(k2.getAlgorithm())) {
 333             System.out.println("DIFFERENT Key Algorithm");
 334             equal = false;
 335         } else if (!k1.getFormat().equalsIgnoreCase(k2.getFormat())) {
 336             System.out.println("DIFFERENT Key Format");
 337             equal = false;
 338         } else if (!Arrays.equals(k1.getEncoded(), k2.getEncoded())) {
 339             System.out.println("DIFFERENT Key Encoding");
 340             equal = false;
 341         }
 342         return equal;
 343     }
 344 }