Utils.java revision 12677:a4299d47bd00
1/*
2 * Copyright (c) 1998, 2014, 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
24import java.security.SecureRandom;
25import javax.crypto.spec.SecretKeySpec;
26
27/**
28 * Helper class.
29 */
30class Utils {
31
32    static final int KEY_SIZE = 70;
33
34    static final String[] MAC_ALGOS = {"HmacMD5", "HmacSHA1", "HmacSHA224",
35        "HmacSHA256", "HmacSHA384", "HmacSHA512"};
36
37    /**
38     * Get SecretKeySpec.
39     */
40    static SecretKeySpec getSecretKeySpec() {
41        SecureRandom srdm = new SecureRandom();
42        byte[] keyVal = new byte[KEY_SIZE];
43        srdm.nextBytes(keyVal);
44        return new SecretKeySpec(keyVal, "HMAC");
45    }
46
47    static void runTests(MacTest... tests) {
48        boolean success = true;
49        for (MacTest test : tests) {
50            success &= runTest(test);
51        }
52
53        if (success) {
54            System.out.println("Test passed");
55        } else {
56            throw new RuntimeException("Test failed");
57        }
58    }
59
60    private static boolean runTest(MacTest test) {
61        boolean success = true;
62        for (String alg : MAC_ALGOS) {
63            try {
64                System.out.println("Test " + alg);
65                test.doTest(alg);
66            } catch (Exception e) {
67                System.out.println("Unexpected exception:");
68                e.printStackTrace();
69                success = false;
70            }
71        }
72
73        return success;
74    }
75}
76
77interface MacTest {
78    void doTest(String alg) throws Exception;
79}
80