码迷,mamicode.com
首页 > 编程语言 > 详细

信息加密之消息摘要算法的MAC

时间:2015-02-10 22:55:30      阅读:323      评论:0      收藏:0      [点我收藏+]

标签:

  MAC是消息摘要算法的第三种实现方式,另外两种方式分别为:MD2\4\5、SHA。

MAC的jdk实现:1、默认密钥方式

private static void MAC_JDK(){
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacMD5");//初始化KeyGenerator
            SecretKey secretKey = keyGenerator.generateKey();//产生密钥
            byte[] key = secretKey.getEncoded();//获得默认密钥
            
            SecretKey restorSecretKey = new SecretKeySpec(key, "HmacMD5");//还原密钥
            Mac mac = Mac.getInstance(restorSecretKey.getAlgorithm());//示例化MAC
            mac.init(restorSecretKey);//初始化MAC
            byte[] hmacMD5Bytes = mac.doFinal(src.getBytes());//执行摘要
            System.out.println("hmacMD5Byte : "+Hex.encodeHexString(hmacMD5Bytes));
        } catch (Exception e) {
            e.printStackTrace();
        }    
    }

2、动态密钥方式:

private static void MAC_JDK_dongtai(){
        try {
            byte[] key = Hex.decodeHex(new char[]{‘a‘,‘a‘,‘a‘,‘a‘,‘a‘,‘a‘,‘a‘,‘a‘,‘a‘,‘a‘});//动态获得密钥
            
            SecretKey restorSecretKey = new SecretKeySpec(key, "HmacMD5");//还原密钥
            Mac mac = Mac.getInstance(restorSecretKey.getAlgorithm());//示例化MAC
            mac.init(restorSecretKey);//初始化MAC
            byte[] hmacMD5Bytes = mac.doFinal(src.getBytes());//执行摘要
            System.out.println("hmacMD5Byte : "+Hex.encodeHexString(hmacMD5Bytes));
        } catch (Exception e) {
            e.printStackTrace();
        }    
    }

MAC的BC实现:

private static void MAC_BC(){
        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[] mac_BC_Byte = new byte[hmac.getMacSize()];//执行摘要
        hmac.doFinal(mac_BC_Byte, 0);
        System.out.println("mac_BC_Byte : "+Hex.encodeHexString(mac_BC_Byte));
    }

  到今天JAVA中的Base64、对称加密、消息摘要加密的实现总结就完工了,如果哪位对此感兴趣,还望多多交流。(1453296946@qq.com)

信息加密之消息摘要算法的MAC

标签:

原文地址:http://www.cnblogs.com/AndroidJotting/p/4284987.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!