当前位置: 移动技术网 > IT编程>开发语言>Java > Java消息摘要算法MAC实现与应用完整示例

Java消息摘要算法MAC实现与应用完整示例

2019年09月09日  | 移动技术网IT编程  | 我要评论

巾帼红颜,京戏脸谱,风槿如画txt新浪

本文实例讲述了java消息摘要算法mac实现与应用。分享给大家供大家参考,具体如下:

一 介绍

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

五 应用场景

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网