package com.dream.util; import javax.crypto.KeyGenerator; import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import junit.framework.TestCase; import org.apache.commons.codec.binary.Hex; import org.bouncycastle.crypto.digests.MD5Digest; import org.bouncycastle.crypto.macs.HMac; import org.bouncycastle.crypto.params.KeyParameter; /** * @author zxg * @see MAC(Message Authentication Code) HMAC(keyed-Hash Message Authentication * Code) 含有密钥的散列函数算法 融合了MD和SHA特性,多了密钥 HmacMD5..,HmacSHA1等 */ public class MACTest extends TestCase { private String str = "zxg is a boy"; /** * jdk hmacMD5 */ public void testjdkHmacMD5() throws Exception { KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacMD5"); SecretKey secretKey = keyGenerator.generateKey();// 产生密钥 byte[] key = Hex.decodeHex("aaaaaaaaaa".toCharArray()); SecretKey restoreSecretKey = new SecretKeySpec(key, "HmacMD5");// 还原密钥 Mac mac = Mac.getInstance(restoreSecretKey.getAlgorithm());// 实例化MAC mac.init(restoreSecretKey);// 初始化Mac byte[] hmacMD5Bytes = mac.doFinal(str.getBytes());// 执行摘要 System.out.println(Hex.encodeHexString(hmacMD5Bytes)); } /** * bc hmacMD5 */ public void testbcHmacMD5() { HMac hmac = new HMac(new MD5Digest()); hmac.init(new KeyParameter(org.bouncycastle.util.encoders.Hex .decode("aaaaaaaaaa"))); hmac.update(str.getBytes(), 0, str.getBytes().length); byte[] hmacMD5bytes = new byte[hmac.getMacSize()]; hmac.doFinal(hmacMD5bytes, 0); System.out.println(org.bouncycastle.util.encoders.Hex .toHexString(hmacMD5bytes)); } }
MAC 密钥散列算法
猜你喜欢
转载自zhizhi555555.iteye.com/blog/2222708
今日推荐
周排行