1/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.conscrypt;
18
19import java.security.Provider;
20import java.security.Security;
21import java.util.Arrays;
22
23import javax.crypto.Mac;
24import javax.crypto.SecretKey;
25import javax.crypto.spec.SecretKeySpec;
26
27import junit.framework.TestCase;
28
29public class MacTest extends TestCase {
30    public void test_getInstance_OpenSSL_ENGINE() throws Exception {
31        final String secret = "-HMAC-test1";
32        final byte[] testString = "testing123".getBytes();
33
34        Provider p = Security.getProvider(OpenSSLProvider.PROVIDER_NAME);
35        NativeCryptoTest.loadTestEngine();
36        OpenSSLEngine engine = OpenSSLEngine.getInstance(NativeCryptoTest.TEST_ENGINE_ID);
37
38        /*
39         * The "-HMAC-" prefix is a special prefix recognized by
40         * test_openssl_engine.cpp
41         */
42        SecretKey key1 = engine.getSecretKeyById(secret, "HmacSHA256");
43        SecretKey key1dupe = engine.getSecretKeyById(secret, "HmacSHA256");
44
45        /* Non-ENGINE-based SecretKey */
46        SecretKey key2 = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
47
48        /* The one that is ENGINE-based can't be equal to a non-ENGINE one. */
49        assertFalse(key1.equals(key2));
50        assertEquals(key1, key1dupe);
51        assertNull(key1.getFormat());
52        assertNull(key1.getEncoded());
53        assertEquals("RAW", key2.getFormat());
54        assertEquals(Arrays.toString(secret.getBytes()), Arrays.toString(key2.getEncoded()));
55
56        Mac mac1 = Mac.getInstance("HmacSHA256", p);
57        mac1.init(key1);
58        mac1.update(testString);
59        byte[] output1 = mac1.doFinal();
60        assertEquals(mac1.getMacLength(), output1.length);
61
62        Mac mac2 = Mac.getInstance("HmacSHA256", p);
63        mac2.init(key2);
64        mac2.update(testString);
65        byte[] output2 = mac2.doFinal();
66
67        assertEquals(Arrays.toString(output2), Arrays.toString(output1));
68    }
69}
70