Path: blob/master/test/jdk/com/sun/crypto/provider/Mac/HmacPBESHA1.java
41159 views
/*1* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/**24* @test25* @bug 4893959 801306926* @summary basic test for PBE MAC algorithms.27* @author Valerie Peng28*/29import java.io.PrintStream;30import java.util.*;31import java.security.*;32import java.security.spec.*;3334import javax.crypto.*;35import javax.crypto.spec.*;3637public class HmacPBESHA1 {38private static final String[] MAC_ALGOS = {39"HmacPBESHA1",40"PBEWithHmacSHA1",41"PBEWithHmacSHA224",42"PBEWithHmacSHA256",43"PBEWithHmacSHA384",44"PBEWithHmacSHA512"45};46private static final int[] MAC_LENGTHS = { 20, 20, 28, 32, 48, 64 };47private static final String KEY_ALGO = "PBE";48private static final String PROVIDER = "SunJCE";4950private static SecretKey key = null;5152public static void main(String argv[]) throws Exception {53for (int i = 0; i < MAC_ALGOS.length; i++) {54runtest(MAC_ALGOS[i], MAC_LENGTHS[i]);55}56System.out.println("\nTest Passed");57}5859private static void runtest(String algo, int length) throws Exception {60System.out.println("Testing: " + algo);61if (key == null) {62char[] password = { 't', 'e', 's', 't' };63PBEKeySpec keySpec = new PBEKeySpec(password);64SecretKeyFactory kf =65SecretKeyFactory.getInstance(KEY_ALGO, PROVIDER);66key = kf.generateSecret(keySpec);67}68Mac mac = Mac.getInstance(algo, PROVIDER);69byte[] plainText = new byte[30];70PBEParameterSpec spec =71new PBEParameterSpec("saltValue".getBytes(), 250);72mac.init(key, spec);73mac.update(plainText);74byte[] value1 = mac.doFinal();75if (value1.length != length) {76throw new Exception("incorrect MAC output length, expected " +77length + ", got " + value1.length);78}79mac.update(plainText);80byte[] value2 = mac.doFinal();81if (!Arrays.equals(value1, value2)) {82throw new Exception("generated different MAC outputs");83}84}85}868788