aboutsummaryrefslogtreecommitdiff
path: root/keystore-cts/java/com/google/security/wycheproof/testcases/MacTest.java
blob: 3a42761e0a5ce37eeff97608e4b48f972ff0f942 (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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
/**
 * 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 java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.junit.After;
import org.junit.Test;
import org.junit.Ignore;
import android.security.keystore.KeyProtection;
import android.security.keystore.KeyProperties;
import android.keystore.cts.util.KeyStoreUtil;

/**
 * Tests for MACs.
 *
 * <p>TODO(bleichen): The tests are quite incomplete. Some of the missing stuff: More test vectors
 * with known results are necessary. So far only simple test vectors for long messages are
 * available.
 */
public class MacTest {
  private static final String EXPECTED_PROVIDER_NAME = TestUtil.EXPECTED_CRYPTO_OP_PROVIDER_NAME;
  private static final String KEY_ALIAS_1 = "TestKey";

  @After
  public void tearDown() throws Exception {
    KeyStoreUtil.cleanUpKeyStore();
  }

  private static Key getKeyStoreSecretKey(byte[] keyMaterial, String algorithm, boolean isStrongBox)
          throws Exception {
      KeyStore keyStore = KeyStoreUtil.saveSecretKeyToKeystore(KEY_ALIAS_1,
                            new SecretKeySpec(keyMaterial, algorithm),
                            new KeyProtection.Builder(KeyProperties.PURPOSE_SIGN)
                                    .setIsStrongBoxBacked(isStrongBox).build());
    return keyStore.getKey(KEY_ALIAS_1, null);
  }

  /**
   * Computes the maximum of an array with at least one element.
   *
   * @param values the values from which the max is computed.
   * @return the maximum
   * @throws IllegalArgumentException if values is empty of null.
   */
  private static int max(int[] values) {
    if (values == null || values.length == 0) {
      throw new IllegalArgumentException("Expecting an array with at least one element");
    }
    int result = Integer.MIN_VALUE;
    for (int value : values) {
      result = Math.max(result, value);
    }
    return result;
  }

  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;
  }

  /**
   * Tests computing a MAC by computing it multiple times. The test passes all the results are the
   * same in all cases.
   *
   * @param algorithm the name of the MAC (e.g. "HMACSHA1")
   * @param key the key of the MAC
   * @param data input data for the MAC. The size of the data must be at least as long as the sum of
   *     all chunkSizes.
   * @param chunkSizes the sizes of the chunks used in the calls of update
   */
  private void testUpdateWithChunks(String algorithm, Key key, byte[] data, int... chunkSizes)
      throws Exception {
    Mac mac = Mac.getInstance(algorithm, EXPECTED_PROVIDER_NAME);

    // First evaluation: compute MAC in one piece.
    int totalLength = 0;
    for (int chunkSize : chunkSizes) {
      totalLength += chunkSize;
    }
    mac.init(key);
    mac.update(data, 0, totalLength);
    byte[] mac1 = mac.doFinal();

    // Second evaluation: using multiple chunks
    mac.init(key);
    int start = 0;
    for (int chunkSize : chunkSizes) {
      mac.update(data, start, chunkSize);
      start += chunkSize;
    }
    byte[] mac2 = mac.doFinal();
    if (!arrayEquals(mac1, mac2)) {
      fail(
          "Different MACs for same input:"
              + " computed as one piece:"
              + TestUtil.bytesToHex(mac1)
              + " computed with multiple array segments:"
              + TestUtil.bytesToHex(mac2));
    }
    // Third evaluation: using ByteBuffers
    mac.init(key);
    start = 0;
    for (int chunkSize : chunkSizes) {
      ByteBuffer chunk = ByteBuffer.wrap(data, start, chunkSize);
      mac.update(chunk);
      start += chunkSize;
    }
    byte[] mac3 = mac.doFinal();
    if (!arrayEquals(mac1, mac3)) {
      fail(
          "Different MACs for same input:"
              + " computed as one piece:"
              + TestUtil.bytesToHex(mac1)
              + " computed with wrapped chunks:"
              + TestUtil.bytesToHex(mac3));
    }
    // Forth evaluation: using ByteBuffer slices.
    // The effect of using slice() is that the resulting ByteBuffer has
    // position 0, but possibly an non-zero value for arrayOffset().
    mac.init(key);
    start = 0;
    for (int chunkSize : chunkSizes) {
      ByteBuffer chunk = ByteBuffer.wrap(data, start, chunkSize).slice();
      mac.update(chunk);
      start += chunkSize;
    }
    byte[] mac4 = mac.doFinal();
    if (!arrayEquals(mac1, mac4)) {
      fail(
          "Different MACs for same input:"
              + " computed as one piece:"
              + TestUtil.bytesToHex(mac1)
              + " computed with ByteBuffer slices:"
              + TestUtil.bytesToHex(mac4));
    }
  }

  /**
   * The paper "Finding Bugs in Cryptographic Hash Function Implementations" by Mouha, Raunak, Kuhn,
   * and Kacker, https://eprint.iacr.org/2017/891.pdf contains an analysis of implementations
   * submitted to the SHA-3 competition. Many of the implementations contain bugs. The authors
   * propose some tests for cryptographic libraries. The test here implements a check for
   * incremental updates with the values proposed in Table 3.
   */
  private void testUpdate(String algorithm, Key key) throws Exception {
    int[] chunkSize1 = {0, 8, 16, 24, 32, 40, 48, 56, 64};
    int[] chunkSize2 = {0, 8, 16, 24, 32, 40, 48, 56, 64};
    int[] chunkSize3 = {0, 8, 16, 32, 64, 128, 256, 512, 1024, 2048};
    int[] chunkSize4 = {
      0, 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, 127, 128, 129, 255, 256,
      257, 511, 512, 513
    };
    int maxSize = max(chunkSize1) + max(chunkSize2) + max(chunkSize3) + max(chunkSize4);
    byte[] data = new byte[maxSize];
    SecureRandom rand = new SecureRandom();
    rand.nextBytes(data);
    for (int size1 : chunkSize1) {
      for (int size2 : chunkSize2) {
        for (int size3 : chunkSize3) {
          for (int size4 : chunkSize4) {
            testUpdateWithChunks(algorithm, key, data, size1, size2, size3, size4);
          }
        }
      }
    }
  }

  public void testMac(String algorithm, int keySize) throws Exception {
    testMac(algorithm, keySize, false);
  }
  public void testMac(String algorithm, int keySize, boolean isStrongBox) throws Exception {
    try {
      Mac.getInstance(algorithm, EXPECTED_PROVIDER_NAME);
    } catch (NoSuchAlgorithmException ex) {
      fail("Algorithm " + algorithm + " is not supported.");
    }
    byte[] key = new byte[keySize];
    SecureRandom rand = new SecureRandom();
    rand.nextBytes(key);
    testUpdate(algorithm, getKeyStoreSecretKey(key, algorithm, isStrongBox));
  }

  @Test
  public void testHmacSha1() throws Exception {
    testMac("HMACSHA1", 20);
  }

  @Test
  public void testHmacSha224() throws Exception {
    testMac("HMACSHA224", 28);
  }

  @Test
  public void testHmacSha256() throws Exception {
    testMac("HMACSHA256", 32);
  }

  @Test
  @Ignore // StrongBox takes very long time to complete this test and CTS timed out (b/242028608), hence ignoring it.
  public void testHmacSha256_StrongBox() throws Exception {
    KeyStoreUtil.assumeStrongBox();
    testMac("HMACSHA256", 32, true);
  }

  @Test
  public void testHmacSha384() throws Exception {
    testMac("HMACSHA384", 48);
  }

  @Test
  public void testHmacSha512() throws Exception {
    testMac("HMACSHA512", 64);
  }

  @Test
  @Ignore // HmacSha3 algorithms are not supported in AndroidKeyStore
  public void testHmacSha3_224() throws Exception {
    testMac("HMACSHA3-224", 28);
  }

  @Test
  @Ignore // HmacSha3 algorithms are not supported in AndroidKeyStore
  public void testHmacSha3_256() throws Exception {
    testMac("HMACSHA3-256", 32);
  }

  @Test
  @Ignore // HmacSha3 algorithms are not supported in AndroidKeyStore
  public void testHmacSha3_384() throws Exception {
    testMac("HMACSHA3-384", 48);
  }

  @Test
  @Ignore // HmacSha3 algorithms are not supported in AndroidKeyStore
  public void testHmacSha3_512() throws Exception {
    testMac("HMACSHA3-512", 64);
  }

  /**
   * Computes the mac of a message repeated multiple times.
   *
   * @param algorithm the message digest (e.g. "HMACSHA1")
   * @param message the bytes to mac
   * @param repetitions the number of repetitions of the message
   * @return the digest
   * @throws GeneralSecurityException if the computation of the mac fails (e.g. because the
   *     algorithm is unknown).
   */
  public byte[] macRepeatedMessage(String algorithm, Key key, byte[] message, long repetitions)
      throws Exception {
    Mac mac = Mac.getInstance(algorithm, EXPECTED_PROVIDER_NAME);
    mac.init(key);
    // If the message is short then it is more efficient to collect multiple copies
    // of the message in one chunk and call update with the larger chunk.
    final int maxChunkSize = 1 << 16;
    if (message.length != 0 && 2 * message.length < maxChunkSize) {
      int repetitionsPerChunk = maxChunkSize / message.length;
      byte[] chunk = new byte[message.length * repetitionsPerChunk];
      for (int i = 0; i < repetitionsPerChunk; i++) {
        System.arraycopy(message, 0, chunk, i * message.length, message.length);
      }
      while (repetitions >= repetitionsPerChunk) {
        mac.update(chunk);
        repetitions -= repetitionsPerChunk;
      }
    }

    for (int i = 0; i < repetitions; i++) {
      mac.update(message);
    }
    return mac.doFinal();
  }

  /**
   * A test for hashing long messages.
   *
   * <p>Java does not allow strings or arrays of size 2^31 or longer. However, it is still possible
   * to compute a MAC of a long message by repeatedly calling Mac.update(). To compute correct MACs
   * the total message length must be known. This length can be bigger than 2^32 bytes.
   *
   * <p>Reference: http://www-01.ibm.com/support/docview.wss?uid=swg1PK62549 IBMJCE SHA-1
   * IMPLEMENTATION RETURNS INCORRECT HASH FOR LARGE SETS OF DATA
   */
  private void testLongMac(
          String algorithm, String keyhex, String message, long repetitions, String expected)
          throws Exception {
    testLongMac(algorithm, keyhex, message, repetitions, expected, false);
  }
  private void testLongMac(
      String algorithm, String keyhex, String message, long repetitions, String expected,
          boolean isStrongBox) throws Exception {

    Key key = getKeyStoreSecretKey(TestUtil.hexToBytes(keyhex), algorithm, isStrongBox);
    byte[] bytes = message.getBytes(UTF_8);
    byte[] mac = null;
    try {
      mac = macRepeatedMessage(algorithm, key, bytes, repetitions);
    } catch (NoSuchAlgorithmException ex) {
      fail("Algorithm " + algorithm + " is not supported.");
    }
    String hexmac = TestUtil.bytesToHex(mac);
    assertEquals(expected, hexmac);
  }

  @Test
  public void testLongMacSha1() throws Exception {
    testLongMac(
        "HMACSHA1",
        "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
        "a",
        2147483647L,
        "703925f6dceb9c602969ad39bba9b1eb49472071");
    testLongMac(
        "HMACSHA1",
        "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
        "a",
        5000000000L,
        "d7f4c387f2237ea119fcc27cd7520fc5132b6230");
  }

  @Test
  public void testLongMacSha256() throws Exception {
    testLongMacSha256(false);
  }
  @Test
  @Ignore // StrongBox takes very long time to complete this test and CTS timed out (b/242028608), hence ignoring it.
  public void testLongMacSha256_StrongBox() throws Exception {
    KeyStoreUtil.assumeStrongBox();
    testLongMacSha256(true);
  }
  private void testLongMacSha256(boolean isStrongBox) throws Exception {
    testLongMac(
        "HMACSHA256",
        "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
        "a",
        2147483647L,
        "84f213c9bb5b329d547bc31dabed41939754b1af7482365ec74380c45f6ea0a7",
        isStrongBox);
    testLongMac(
        "HMACSHA256",
        "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
        "a",
        5000000000L,
        "59a75754df7093fa4339aa618b64b104f153a5b42cc85394fdb8735b13ea684a",
        isStrongBox);
  }

  @Test
  public void testLongMacSha384() throws Exception {
    testLongMac(
        "HMACSHA384",
        "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"
            + "202122232425262728292a2b2c2d2e2f",
        "a",
        2147483647L,
        "aea987905f64791691b3fdea06f8e4125f396ebb73f37894e961b1a7522a55da"
            + "ecd856a70c92c6646e6f8c3fcb935528");
    testLongMac(
        "HMACSHA384",
        "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"
            + "202122232425262728292a2b2c2d2e2f",
        "a",
        5000000000L,
        "88485c9c5714d43a99dacbc861988c7ea39c02d82104bf93e55ec1b8a24fe15a"
            + "a477e6a84d159d8b7a3daaa89c4f2372");
  }

  @Test
  public void testLongMacSha512() throws Exception {
    testLongMac(
        "HMACSHA512",
        "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"
            + "202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f",
        "a",
        2147483647L,
        "fc68fbc294951c691e5bc085c3af026099f39a57230b242aaf1fc5ca691e05da"
            + "d1a5de7d4f30e1c958c6a2cee6159218dab683187e6d56bab824a3adefde9102");
    testLongMac(
        "HMACSHA512",
        "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"
            + "202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f",
        "a",
        5000000000L,
        "31b1d721b958203bff7d7ddf50d48b17fc760a80a99a7f23ec966ce3bbefff29"
            + "0d176eebbb6a440960024be0726c94960bbf75816548a7fd4552c7baba4585ee");
  }
}