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