消息摘要算法MAC实现与应用

187 篇文章 33 订阅
一 介绍
MAC:Message Authentication Code
HMAC:keyed-Hash Message Authencication Code,含有密钥的散列函数算法。
融合MD、SHA
MD系列:HmacMD2、HmacMD4、HmacMD5
SHA系列:HmacSHA1、HmacSHA224、HmacSHA256、HmacSHA384、HmacSHA512
应用:SecureCRT

二 参数说明

三 代码实现
package com.imooc.security.hmac;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

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;

public class ImoocHmac {
	
	private static String src = "cakin24 security hmac";

	public static void main(String[] args) {
		 jdkHmacMD5();
		 bcHmacMD5();
	}
	
	public static void jdkHmacMD5() {
		try {
			KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacMD5");//初始化KeyGenerator
			SecretKey secretKey = keyGenerator.generateKey();//产生密钥
//			byte[] key = secretKey.getEncoded();//获得密钥
			byte[] key = Hex.decodeHex(new char[] {'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a'});
			
			SecretKey restoreSecretKey = new SecretKeySpec(key, "HmacMD5");//还原密钥
			Mac mac = Mac.getInstance(restoreSecretKey.getAlgorithm());//实例化MAC
			mac.init(restoreSecretKey);//初始化Mac
			byte[] hmacMD5Bytes = mac.doFinal(src.getBytes());//执行摘要
			System.out.println("jdk hmacMD5 : " + Hex.encodeHexString(hmacMD5Bytes));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void bcHmacMD5() {
		HMac hmac = new HMac(new MD5Digest());
		hmac.init(new KeyParameter(org.bouncycastle.util.encoders.Hex.decode("aaaaaaaaaa")));
		hmac.update(src.getBytes(), 0, src.getBytes().length);
		
		byte[] hmacMD5Bytes = new byte[hmac.getMacSize()];//执行摘要
		hmac.doFinal(hmacMD5Bytes, 0);
		
		System.out.println("bc hmacMD5 : " + org.bouncycastle.util.encoders.Hex.toHexString(hmacMD5Bytes));	
	}
}

四 实现效果
jdk hmacMD5 : d23aa029b2bacdd3979d10f0931f9af6
bc hmacMD5 : d23aa029b2bacdd3979d10f0931f9af6

五 应用场景
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值