MAC (Message Authentication Code,消息认证码算法)

需要将密钥发送到对方,对方用该密钥进行摘要处理,进行摘要验证。

//初始化KeyGenerator
KeyGenerator keyGenerator= KeyGenerator.getInstance("HmacMd5");
//出生密钥
SecretKey secretKey=KeyGenerator.generator();
//获得密钥
byte[] key=secretKey.getEncoded();


//还原,获得密钥
SecretKey seretKey= new SecretKeySpec(key, "HmacMD5");
//做消息摘要
Mac mc=Mac.getInstance(secretKey.getAlgorithm());
//初始化MAC
mac.init(secretKey);
//执行消息摘要
byte[] data=mac.doFinal(data);

public  class  MACode {

         //产生密钥
         public  static  byte [] initHmacMD5Key()  throws  Exception{
              KeyGenerator keyGenerator=KeyGenerator. getInstance( "HmacMD5" );
//            KeyGenerator keyGenerator=KeyGenerator.getInstance("HmacSHA1");
//            KeyGenerator keyGenerator=KeyGenerator.getInstance("HmacSHA256");
//            KeyGenerator keyGenerator=KeyGenerator.getInstance("HmacSHA384");
//            KeyGenerator keyGenerator=KeyGenerator.getInstance("HmacSHA512");
              
              SecretKey secretKey=keyGenerator.generateKey();
                return  secretKey.getEncoded();
       }
       
         //进行消息摘要
         public  static  byte [] encodeHmacMD5( byte [] data,  byte [] key)  throws  Exception{
                //还原密钥
              SecretKey secretKey=  new  SecretKeySpec(key, "HmacMD5"  );
//            SecretKey secretKey=new SecretKeySpec(key,"HmacSHA1");
//            SecretKey secretKey=new SecretKeySpec(key,"HmacSHA256");
//            SecretKey secretKey=new SecretKeySpec(key,"HmacSHA384");
//            SecretKey secretKey=new SecretKeySpec(key,"HmacSHA512");
              
                //实例化mac
              Mac mac=Mac. getInstance(secretKey.getAlgorithm());
                //初始化mac
              mac.init(secretKey);
                //返回消息摘要
                return  mac.doFinal(data);
       }

         public  static  final  void  main(String[] args)  throws  Exception{
              String str=  "MAC消息摘要"  ;
                //初始化密钥
                byte [] b=initHmacMD5Key();
                //获取消息摘要
                byte [] data=encodeHmacMD5(str.getBytes(), b);
              System.  out .println( new  String(Hex.encode(data)));  //进行十六进制处理
       }
}

转载于:https://www.cnblogs.com/littlefishxu/p/3969179.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值