分享

Java 加解密技术系列之 HMAC

 nikybook 2016-01-08
  1. <span style="font-family:Comic Sans MS;font-size:12px;">package com.sica.hmac;  

  2. import com.google.common.base.Strings;  

  3. import sun.misc.BASE64Decoder;  

  4. import sun.misc.BASE64Encoder;  

  5. import javax.crypto.KeyGenerator;  

  6. import javax.crypto.Mac;  

  7. import javax.crypto.SecretKey;  

  8. import javax.crypto.spec.SecretKeySpec;  

  9. import java.security.NoSuchAlgorithmException;  

  10. /** 

  11.  * Created by xiang.li on 2015/2/27. 

  12.  */  

  13. public class HMAC {  

  14.     /** 

  15.      * 定义加密方式 

  16.      * MAC算法可选以下多种算法 

  17.      * <pre> 

  18.      * HmacMD5 

  19.      * HmacSHA1 

  20.      * HmacSHA256 

  21.      * HmacSHA384 

  22.      * HmacSHA512 

  23.      * </pre> 

  24.      */  

  25.     private final static String KEY_MAC = "HmacMD5";  

  26.     /** 

  27.      * 全局数组 

  28.      */  

  29.     private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5",  

  30.             "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };  

  31.     /** 

  32.      * 构造函数 

  33.      */  

  34.     public HMAC() {  

  35.     }  

  36.     /** 

  37.      * BASE64 加密 

  38.      * @param key 需要加密的字节数组 

  39.      * @return 字符串 

  40.      * @throws Exception 

  41.      */  

  42.     public static String encryptBase64(byte[] key) throws Exception {  

  43.         return (new BASE64Encoder()).encodeBuffer(key);  

  44.     }  

  45.     /** 

  46.      * BASE64 解密 

  47.      * @param key 需要解密的字符串 

  48.      * @return 字节数组 

  49.      * @throws Exception 

  50.      */  

  51.     public static byte[] decryptBase64(String key) throws Exception {  

  52.         return (new BASE64Decoder()).decodeBuffer(key);  

  53.     }  

  54.     /** 

  55.      * 初始化HMAC密钥 

  56.      * @return 

  57.      */  

  58.     public static String init() {  

  59.         SecretKey key;  

  60.         String str = "";  

  61.         try {  

  62.             KeyGenerator generator = KeyGenerator.getInstance(KEY_MAC);  

  63.             key = generator.generateKey();  

  64.             str = encryptBase64(key.getEncoded());  

  65.         } catch (NoSuchAlgorithmException e) {  

  66.             e.printStackTrace();  

  67.         } catch (Exception e) {  

  68.             e.printStackTrace();  

  69.         }  

  70.         return str;  

  71.     }  

  72.     /** 

  73.      * HMAC加密 

  74.      * @param data 需要加密的字节数组 

  75.      * @param key 密钥 

  76.      * @return 字节数组 

  77.      */  

  78.     public static byte[] encryptHMAC(byte[] data, String key) {  

  79.         SecretKey secretKey;  

  80.         byte[] bytes = null;  

  81.         try {  

  82.             secretKey = new SecretKeySpec(decryptBase64(key), KEY_MAC);  

  83.             Mac mac = Mac.getInstance(secretKey.getAlgorithm());  

  84.             mac.init(secretKey);  

  85.             bytes = mac.doFinal(data);  

  86.         } catch (Exception e) {  

  87.             e.printStackTrace();  

  88.         }  

  89.         return bytes;  

  90.     }  

  91.     /** 

  92.      * HMAC加密 

  93.      * @param data 需要加密的字符串 

  94.      * @param key 密钥 

  95.      * @return 字符串 

  96.      */  

  97.     public static String encryptHMAC(String data, String key) {  

  98.         if (Strings.isNullOrEmpty(data)) {  

  99.             return null;  

  100.         }  

  101.         byte[] bytes = encryptHMAC(data.getBytes(), key);  

  102.         return byteArrayToHexString(bytes);  

  103.     }  

  104.     /** 

  105.      * 将一个字节转化成十六进制形式的字符串 

  106.      * @param b 字节数组 

  107.      * @return 字符串 

  108.      */  

  109.     private static String byteToHexString(byte b) {  

  110.         int ret = b;  

  111.         //System.out.println("ret = " + ret);  

  112.         if (ret < 0) {  

  113.             ret += 256;  

  114.         }  

  115.         int m = ret / 16;  

  116.         int n = ret % 16;  

  117.         return hexDigits[m] + hexDigits[n];  

  118.     }  

  119.     /** 

  120.      * 转换字节数组为十六进制字符串 

  121.      * @param bytes 字节数组 

  122.      * @return 十六进制字符串 

  123.      */  

  124.     private static String byteArrayToHexString(byte[] bytes) {  

  125.         StringBuffer sb = new StringBuffer();  

  126.         for (int i = 0; i < bytes.length; i++) {  

  127.             sb.append(byteToHexString(bytes[i]));  

  128.         }  

  129.         return sb.toString();  

  130.     }  

  131.     /** 

  132.      * 测试方法 

  133.      * @param args 

  134.      */  

  135.     public static void main(String[] args) throws Exception {  

  136.         String key = HMAC.init();  

  137.         System.out.println("Mac密钥:\n" + key);  

  138.         String word = "123";  

  139.         System.out.println(encryptHMAC(word, key));  

  140.     }  

  141. }</span>  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约