1 /*
   2  * Copyright (c) 2018, 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 8153029
  27  * @summary ChaCha20 Cipher Implementation (parameters)
  28  */
  29 
  30 import java.util.*;
  31 import java.io.IOException;
  32 import java.security.GeneralSecurityException;
  33 import javax.crypto.Cipher;
  34 import javax.crypto.spec.ChaCha20ParameterSpec;
  35 import javax.crypto.spec.IvParameterSpec;
  36 import javax.crypto.spec.SecretKeySpec;
  37 import javax.crypto.AEADBadTagException;
  38 import java.security.AlgorithmParameters;
  39 import java.security.NoSuchAlgorithmException;
  40 import java.nio.ByteBuffer;
  41 
  42 public class ChaCha20Poly1305ParamTest {
  43     public static class TestData {
  44         public TestData(String name, String keyStr, String nonceStr, int ctr,
  45                 int dir, String inputStr, String aadStr, String outStr) {
  46             testName = Objects.requireNonNull(name);
  47             key = hex2bin(Objects.requireNonNull(keyStr));
  48             nonce = hex2bin(Objects.requireNonNull(nonceStr));
  49             if ((counter = ctr) < 0) {
  50                 throw new IllegalArgumentException(
  51                         "counter must be 0 or greater");
  52             }
  53             direction = dir;
  54             if ((direction != Cipher.ENCRYPT_MODE) &&
  55                     (direction != Cipher.DECRYPT_MODE)) {
  56                 throw new IllegalArgumentException(
  57                         "Direction must be ENCRYPT_MODE or DECRYPT_MODE");
  58             }
  59             input = hex2bin(Objects.requireNonNull(inputStr));
  60             aad = (aadStr != null) ? hex2bin(aadStr) : null;
  61             expOutput = hex2bin(Objects.requireNonNull(outStr));
  62         }
  63 
  64         public final String testName;
  65         public final byte[] key;
  66         public final byte[] nonce;
  67         public final int counter;
  68         public final int direction;
  69         public final byte[] input;
  70         public final byte[] aad;
  71         public final byte[] expOutput;
  72     }
  73 
  74     public static final List<TestData> aeadTestList =
  75             new LinkedList<TestData>() {{
  76         add(new TestData("RFC 7539 Sample AEAD Test Vector",
  77             "808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f",
  78             "070000004041424344454647",
  79             1, Cipher.ENCRYPT_MODE,
  80             "4c616469657320616e642047656e746c656d656e206f662074686520636c6173" +
  81             "73206f66202739393a204966204920636f756c64206f6666657220796f75206f" +
  82             "6e6c79206f6e652074697020666f7220746865206675747572652c2073756e73" +
  83             "637265656e20776f756c642062652069742e",
  84             "50515253c0c1c2c3c4c5c6c7",
  85             "d31a8d34648e60db7b86afbc53ef7ec2a4aded51296e08fea9e2b5a736ee62d6" +
  86             "3dbea45e8ca9671282fafb69da92728b1a71de0a9e060b2905d6a5b67ecd3b36" +
  87             "92ddbd7f2d778b8c9803aee328091b58fab324e4fad675945585808b4831d7bc" +
  88             "3ff4def08e4b7a9de576d26586cec64b61161ae10b594f09e26a7e902ecbd060" +
  89             "0691"));
  90         add(new TestData("RFC 7539 A.5 Sample Decryption",
  91             "1c9240a5eb55d38af333888604f6b5f0473917c1402b80099dca5cbc207075c0",
  92             "000000000102030405060708",
  93             1, Cipher.DECRYPT_MODE,
  94             "64a0861575861af460f062c79be643bd5e805cfd345cf389f108670ac76c8cb2" +
  95             "4c6cfc18755d43eea09ee94e382d26b0bdb7b73c321b0100d4f03b7f355894cf" +
  96             "332f830e710b97ce98c8a84abd0b948114ad176e008d33bd60f982b1ff37c855" +
  97             "9797a06ef4f0ef61c186324e2b3506383606907b6a7c02b0f9f6157b53c867e4" +
  98             "b9166c767b804d46a59b5216cde7a4e99040c5a40433225ee282a1b0a06c523e" +
  99             "af4534d7f83fa1155b0047718cbc546a0d072b04b3564eea1b422273f548271a" +
 100             "0bb2316053fa76991955ebd63159434ecebb4e466dae5a1073a6727627097a10" +
 101             "49e617d91d361094fa68f0ff77987130305beaba2eda04df997b714d6c6f2c29" +
 102             "a6ad5cb4022b02709beead9d67890cbb22392336fea1851f38",
 103             "f33388860000000000004e91",
 104             "496e7465726e65742d4472616674732061726520647261667420646f63756d65" +
 105             "6e74732076616c696420666f722061206d6178696d756d206f6620736978206d" +
 106             "6f6e74687320616e64206d617920626520757064617465642c207265706c6163" +
 107             "65642c206f72206f62736f6c65746564206279206f7468657220646f63756d65" +
 108             "6e747320617420616e792074696d652e20497420697320696e617070726f7072" +
 109             "6961746520746f2075736520496e7465726e65742d4472616674732061732072" +
 110             "65666572656e6365206d6174657269616c206f7220746f206369746520746865" +
 111             "6d206f74686572207468616e206173202fe2809c776f726b20696e2070726f67" +
 112             "726573732e2fe2809d"));
 113     }};
 114 
 115     // 12-byte nonce DER-encoded as an OCTET_STRING
 116     public static final byte[] NONCE_OCTET_STR_12 = {
 117         4, 12, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8
 118     };
 119 
 120     // Invalid 16-byte nonce DER-encoded as an OCTET_STRING
 121     public static final byte[] NONCE_OCTET_STR_16 = {
 122         4, 16, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
 123     };
 124 
 125     public static void main(String args[]) throws Exception {
 126         int testsPassed = 0;
 127         int testNumber = 0;
 128 
 129         // Try (and hopefully fail) to create a ChaCha20 AlgorithmParameterSpec
 130         System.out.println(
 131                 "*** Test: Try to make ChaCha20 AlgorithmParameterSpec");
 132         try {
 133             ChaCha20ParameterSpec badChaCha20Spec =
 134                     new ChaCha20ParameterSpec(NONCE_OCTET_STR_16, 1);
 135             throw new RuntimeException("ChaCha20 AlgorithmParameterSpec " +
 136                     "with 16 byte nonce should fail");
 137         } catch (IllegalArgumentException iae) {
 138             System.out.println("Caught expected exception: " + iae);
 139         }
 140         
 141         // Try (and hopefully fail) to create a ChaCha20 AlgorithmParameters
 142         System.out.println(
 143                 "*** Test: Try to make ChaCha20 AlgorithmParameters");
 144         try {
 145             AlgorithmParameters apsNoChaCha20 =
 146                     AlgorithmParameters.getInstance("ChaCha20");
 147             throw new RuntimeException(
 148                     "ChaCha20 AlgorithmParameters should fail");
 149         } catch (NoSuchAlgorithmException nsae) {
 150             System.out.println("Caught expected exception: " + nsae);
 151         }
 152 
 153         // Create the AlgorithmParameter object from a valid encoding
 154         System.out.println("*** Test: Create and init ChaCha20-Poly1305 APS");
 155         AlgorithmParameters apsGood =
 156                 AlgorithmParameters.getInstance("ChaCha20-Poly1305");
 157         apsGood.init(NONCE_OCTET_STR_12);
 158         System.out.println("Test Passed");
 159 
 160         // Create and try to init using invalid encoding
 161         AlgorithmParameters apsBad =
 162                 AlgorithmParameters.getInstance("ChaCha20-Poly1305");
 163         System.out.println("*** Test: Use invalid encoding scheme");
 164         try {
 165             apsBad.init(NONCE_OCTET_STR_12, "OraclePrivate");
 166         } catch (IllegalArgumentException iae) {
 167             System.out.println("Caught expected exception: " + iae);
 168         }
 169 
 170         // Try to init using supported scheme but invalid length
 171         System.out.println("*** Test: Use supported scheme, nonce too large");
 172         try {
 173             apsBad.init(NONCE_OCTET_STR_16, "ASN.1");
 174         } catch (IOException ioe) {
 175             System.out.println("Caught expected exception: " + ioe);
 176         }
 177 
 178         System.out.println("----- AEAD Tests -----");
 179         for (TestData test : aeadTestList) {
 180             System.out.println("*** Test " + ++testNumber + ": " +
 181                     test.testName);
 182             if (runAEADTest(test)) {
 183                 testsPassed++;
 184             }
 185         }
 186         System.out.println();
 187 
 188         System.out.println("Total tests: " + testNumber +
 189                 ", Passed: " + testsPassed + ", Failed: " +
 190                 (testNumber - testsPassed));
 191         if (testsPassed != testNumber) {
 192             throw new RuntimeException("One or more tests failed.  " +
 193                     "Check output for details");
 194         }
 195     }
 196 
 197 
 198     private static boolean runAEADTest(TestData testData)
 199             throws GeneralSecurityException, IOException {
 200         boolean result = false;
 201 
 202         Cipher mambo = Cipher.getInstance("ChaCha20-Poly1305");
 203         SecretKeySpec mamboKey = new SecretKeySpec(testData.key, "ChaCha20");
 204         AlgorithmParameters mamboParams =
 205                 AlgorithmParameters.getInstance("ChaCha20-Poly1305");
 206 
 207         // Put the nonce into ASN.1 ChaCha20-Poly1305 parameter format
 208         byte[] derNonce = new byte[testData.nonce.length + 2];
 209         derNonce[0] = 0x04;
 210         derNonce[1] = (byte)testData.nonce.length;
 211         System.arraycopy(testData.nonce, 0, derNonce, 2,
 212                 testData.nonce.length);
 213         mamboParams.init(derNonce);
 214 
 215         mambo.init(testData.direction, mamboKey, mamboParams);
 216 
 217         byte[] out = new byte[mambo.getOutputSize(testData.input.length)];
 218         int outOff = 0;
 219         try {
 220             mambo.updateAAD(testData.aad);
 221             outOff += mambo.update(testData.input, 0, testData.input.length,
 222                     out, outOff);
 223             outOff += mambo.doFinal(out, outOff);
 224         } catch (AEADBadTagException abte) {
 225             // If we get a bad tag or derive a tag mismatch, log it
 226             // and register it as a failure
 227             System.out.println("FAIL: " + abte);
 228             return false;
 229         }
 230 
 231         if (!Arrays.equals(out, testData.expOutput)) {
 232             System.out.println("ERROR - Output Mismatch!");
 233             System.out.println("Expected:\n" +
 234                     dumpHexBytes(testData.expOutput, 16, "\n", " "));
 235             System.out.println("Actual:\n" +
 236                     dumpHexBytes(out, 16, "\n", " "));
 237             System.out.println();
 238         } else {
 239             result = true;
 240         }
 241 
 242         return result;
 243     }
 244 
 245     /**
 246      * Dump the hex bytes of a buffer into string form.
 247      *
 248      * @param data The array of bytes to dump to stdout.
 249      * @param itemsPerLine The number of bytes to display per line
 250      *      if the {@code lineDelim} character is blank then all bytes
 251      *      will be printed on a single line.
 252      * @param lineDelim The delimiter between lines
 253      * @param itemDelim The delimiter between bytes
 254      *
 255      * @return The hexdump of the byte array
 256      */
 257     private static String dumpHexBytes(byte[] data, int itemsPerLine,
 258             String lineDelim, String itemDelim) {
 259         return dumpHexBytes(ByteBuffer.wrap(data), itemsPerLine, lineDelim,
 260                 itemDelim);
 261     }
 262 
 263     private static String dumpHexBytes(ByteBuffer data, int itemsPerLine,
 264             String lineDelim, String itemDelim) {
 265         StringBuilder sb = new StringBuilder();
 266         if (data != null) {
 267             data.mark();
 268             int i = 0;
 269             while (data.remaining() > 0) {
 270                 if (i % itemsPerLine == 0 && i != 0) {
 271                     sb.append(lineDelim);
 272                 }
 273                 sb.append(String.format("%02X", data.get())).append(itemDelim);
 274                 i++;
 275             }
 276             data.reset();
 277         }
 278 
 279         return sb.toString();
 280     }
 281 
 282     private static byte[] hex2bin(String hex) {
 283         int i;
 284         int len = hex.length();
 285         byte[] data = new byte [len / 2];
 286         for (i = 0; i < len; i += 2) {
 287             data[i / 2] = (byte)((Character.digit(hex.charAt(i), 16) << 4) +
 288                     Character.digit(hex.charAt(i + 1), 16));
 289         }
 290         return data;
 291     }
 292 
 293 }