aboutsummaryrefslogtreecommitdiff
path: root/keystore-cts/java/com/google/security/wycheproof/testcases/JsonMacTest.java
blob: eeb48ecf5d00fcd51dbba5c9c46902eff3759eb0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
/**
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * <p>http://www.apache.org/licenses/LICENSE-2.0
 *
 * <p>Unless required by applicable law or agreed to in writing, software distributed under the
 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.security.wycheproof;

import static org.junit.Assert.assertEquals;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.security.GeneralSecurityException;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Locale;
import javax.crypto.Mac;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** This test uses test vectors in JSON format to test MAC primitives. */
@RunWith(JUnit4.class)
public class JsonMacTest {

  /** Convenience method to get a byte array from an JsonObject */
  protected static byte[] getBytes(JsonObject obj, String name) throws Exception {
    return JsonUtil.asByteArray(obj.get(name));
  }

  protected static boolean arrayEquals(byte[] a, byte[] b) {
    if (a.length != b.length) {
      return false;
    }
    byte res = 0;
    for (int i = 0; i < a.length; i++) {
      res |= (byte) (a[i] ^ b[i]);
    }
    return res == 0;
  }

  /**
   * Computes a MAC.
   *
   * @param algorithm the algorithm.
   * @param key the key bytes
   * @param msg the message to MAC.
   * @param tagSize the expected size of the tag in bits.
   * @return the tag
   * @throws GeneralSecurityException if the algorithm or the parameter sizes are not supported or
   *     if the initialization failed. For example one case are GMACs with a tag size othe than 128
   *     bits, since the JCE interface does not seem to support such a specification.
   */
  protected static byte[] computeMac(String algorithm, byte[] key, byte[] msg, int tagSize)
      throws GeneralSecurityException {
    Mac mac = Mac.getInstance(algorithm);
    algorithm = algorithm.toUpperCase(Locale.ENGLISH);
    if (algorithm.startsWith("HMAC")) {
      SecretKeySpec keySpec = new SecretKeySpec(key, algorithm);
      // TODO(bleichen): Is there a provider independent truncation?
      //   The class javax.xml.crypto.dsig.spec.HMACParameterSpec would allow to
      //   truncate HMAC tags as follows:
      //   <pre>
      //     HMACParameterSpec params = new HMACParameterSpec(tagSize);
      //     mac.init(keySpec, params);
      //     mac.update(msg);
      //     return mac.doFinal();
      //   </pre>
      //   But this class is often not supported. Hence the computation here, just computes a
      //   full length tag and truncates it. The drawback of having to truncate tags is that
      //   the caller has to compare truncated tags during verification.
      mac.init(keySpec);
      mac.update(msg);
      byte[] tag = mac.doFinal();
      return Arrays.copyOf(tag, tagSize / 8);
    } else {
      throw new NoSuchAlgorithmException(algorithm);
    }
  }

  /**
   * Tests a randomized MAC (i.e. a message authetication that takes an additional IV as parameter)
   * against test vectors.
   *
   * @param filename the JSON file with the test vectors.
   */
  public void testMac(String filename) throws Exception {
    // Checking preconditions.
    JsonObject test = JsonUtil.getTestVectors(filename);
    String algorithm = test.get("algorithm").getAsString();
    try {
      Mac.getInstance(algorithm);
    } catch (NoSuchAlgorithmException ex) {
      System.out.println("Algorithm is not supported. Skipping test for " + algorithm);
      return;
    }

    int numTests = test.get("numberOfTests").getAsInt();
    int cntTests = 0;
    int passedTests = 0;
    int errors = 0;
    for (JsonElement g : test.getAsJsonArray("testGroups")) {
      JsonObject group = g.getAsJsonObject();
      int tagSize = group.get("tagSize").getAsInt();
      for (JsonElement t : group.getAsJsonArray("tests")) {
        cntTests++;
        JsonObject testcase = t.getAsJsonObject();
        int tcid = testcase.get("tcId").getAsInt();
        String tc = "tcId: " + tcid + " " + testcase.get("comment").getAsString();
        byte[] key = getBytes(testcase, "key");
        byte[] msg = getBytes(testcase, "msg");
        byte[] expectedTag = getBytes(testcase, "tag");
        // Result is one of "valid", "invalid", "acceptable".
        // "valid" are test vectors with matching plaintext, ciphertext and tag.
        // "invalid" are test vectors with invalid parameters or invalid ciphertext and tag.
        // "acceptable" are test vectors with weak parameters or legacy formats.
        String result = testcase.get("result").getAsString();

        byte[] computedTag = null;
        try {
          computedTag = computeMac(algorithm, key, msg, tagSize);
        } catch (GeneralSecurityException ex) {
          // Some libraries restrict key size or tag size. Hence valid MACs might be
          // rejected.
          continue;
        } catch (IllegalArgumentException ex) {
          // Thrown by javax.crypto.spec.SecretKeySpec (e.g. when the key is empty).
          continue;
        }

        boolean eq = arrayEquals(expectedTag, computedTag);
        if (result.equals("invalid")) {
          if (eq) {
            // Some test vectors use invalid parameters that should be rejected.
            // E.g. an implementation must not allow AES-GMAC with an IV of length 0,
            // since this leaks the authentication key.
            System.out.println("Computed mac for test case " + tc);
            errors++;
          }
        } else {
          if (eq) {
            passedTests++;
          } else {
            System.out.println(
                "Incorrect tag for "
                    + tc
                    + " expected:"
                    + TestUtil.bytesToHex(expectedTag)
                    + " computed:"
                    + TestUtil.bytesToHex(computedTag));
            errors++;
          }
        }
      }
    }
    System.out.println("passed Tests for " + algorithm + ":" + passedTests);
    assertEquals(0, errors);
    assertEquals(numTests, cntTests);
  }

  /**
   * Returns an initialized instance of a randomized MAC.
   *
   * @param algorithm the algorithm.
   * @param key the key bytes
   * @param iv the bytes of the initialization vector
   * @param tagSize the expected size of the tag in bits.
   * @return an initialized instance of a MAC.
   * @throws GeneralSecurityException if the algorithm or the parameter sizes are not supported or
   *     if the initialization failed. For example one case are GMACs with a tag size othe than 128
   *     bits, since the JCE interface does not seem to support such a specification.
   */
  protected static Mac getInitializedMacWithIv(String algorithm, byte[] key, byte[] iv, int tagSize)
      throws GeneralSecurityException {
    Mac mac = Mac.getInstance(algorithm);
    algorithm = algorithm.toUpperCase(Locale.ENGLISH);
    if (algorithm.equals("AES-GMAC")) {
      SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
      if (tagSize != 128) {
        throw new InvalidAlgorithmParameterException("only 128-bit tag is supported");
      }
      IvParameterSpec params = new IvParameterSpec(iv);
      // TODO(bleichen): I'm unaware of a method that allows to specify the tag size in JCE.
      //   E.g. the following parameter specification does not work (at least not in BC):
      //   GCMParameterSpec params = new GCMParameterSpec(tagSize, iv);
      mac.init(keySpec, params);
      return mac;
    } else {
      throw new NoSuchAlgorithmException(algorithm);
    }
  }

  /**
   * Tests a randomized MAC (i.e. a message authetication that takes an additional IV as
   * parameter) against test vectors.
   *
   * @param filename the JSON file with the test vectors.
   * @param algorithm the JCE name of the algorithm to test.
   */
  public void testMacWithIv(String filename, String algorithm) throws Exception {
    // Checking preconditions.
    try {
      Mac.getInstance(algorithm);
    } catch (NoSuchAlgorithmException ex) {
      System.out.println("Algorithm is not supported. Skipping test for " + algorithm);
      return;
    }

    JsonObject test = JsonUtil.getTestVectors(filename);
    int numTests = test.get("numberOfTests").getAsInt();
    int cntTests = 0;
    int passedTests = 0;
    int errors = 0;
    for (JsonElement g : test.getAsJsonArray("testGroups")) {
      JsonObject group = g.getAsJsonObject();
      int tagSize = group.get("tagSize").getAsInt();
      for (JsonElement t : group.getAsJsonArray("tests")) {
        cntTests++;
        JsonObject testcase = t.getAsJsonObject();
        int tcid = testcase.get("tcId").getAsInt();
        String tc = "tcId: " + tcid + " " + testcase.get("comment").getAsString();
        byte[] key = getBytes(testcase, "key");
        byte[] iv = getBytes(testcase, "iv");
        byte[] msg = getBytes(testcase, "msg");
        byte[] expectedTag = getBytes(testcase, "tag");
        // Result is one of "valid", "invalid", "acceptable".
        // "valid" are test vectors with matching plaintext, ciphertext and tag.
        // "invalid" are test vectors with invalid parameters or invalid ciphertext and tag.
        // "acceptable" are test vectors with weak parameters or legacy formats.
        String result = testcase.get("result").getAsString();

        Mac mac;
        try {
          mac = getInitializedMacWithIv(algorithm, key, iv, tagSize);
        } catch (GeneralSecurityException ex) {
          // Some libraries restrict key size, iv size and tag size.
          // Because of the initialization of the Mac might fail.
          continue;
        } catch (IllegalArgumentException ex) {
          // Thrown by javax.crypto.spec.SecretKeySpec (e.g. when the key is empty).
          continue;
        }

        byte[] computedTag = mac.doFinal(msg);
        boolean eq = arrayEquals(expectedTag, computedTag);
        if (result.equals("invalid")) {
          if (eq) {
            // Some test vectors use invalid parameters that should be rejected.
            // E.g. an implementation must not allow AES-GMAC with an IV of length 0,
            // since this leaks the authentication key.
            System.out.println("Computed mac for test case " + tc);
            errors++;
          }
        } else {
          if (eq) {
            passedTests++;
          } else {
            System.out.println(
                "Incorrect tag for "
                    + tc
                    + " expected:"
                    + TestUtil.bytesToHex(expectedTag)
                    + " computed:"
                    + TestUtil.bytesToHex(computedTag));
            errors++;
          }
        }
      }
    }
    System.out.println("passed Tests for " + algorithm + ":" + passedTests);
    assertEquals(0, errors);
    assertEquals(numTests, cntTests);
  }

  @Test
  public void testHmacSha1() throws Exception {
    testMac("hmac_sha1_test.json");
  }

  @Test
  public void testHmacSha224() throws Exception {
    testMac("hmac_sha224_test.json");
  }

  @Test
  public void testHmacSha256() throws Exception {
    testMac("hmac_sha256_test.json");
  }

  @Test
  public void testHmacSha384() throws Exception {
    testMac("hmac_sha384_test.json");
  }

  @Test
  public void testHmacSha512() throws Exception {
    testMac("hmac_sha512_test.json");
  }

  @Test
  public void testHmacSha3_224() throws Exception {
    testMac("hmac_sha3_224_test.json");
  }

  @Test
  public void testHmacSha3_256() throws Exception {
    testMac("hmac_sha3_256_test.json");
  }

  @Test
  public void testHmacSha3_384() throws Exception {
    testMac("hmac_sha3_384_test.json");
  }

  @Test
  public void testHmacSha3_512() throws Exception {
    testMac("hmac_sha3_512_test.json");
  }

  @Test
  public void testAesGmac() throws Exception {
    testMacWithIv("gmac_test.json", "AES-GMAC");
  }
}