HMACSHA1算法的JAVA实现

 1 import javax.crypto.Mac;
 2 import javax.crypto.SecretKey;
 3 import javax.crypto.spec.SecretKeySpec;
 4 
 5 public class HMACSHA1 {
 6 
 7     private static final String MAC_NAME = "HmacSHA1";  
 8     private static final String ENCODING = "UTF-8";  
 9     
10     /*
11      * 展示了一个生成指定算法密钥的过程 初始化HMAC密钥 
12      * @return 
13      * @throws Exception
14      * 
15       public static String initMacKey() throws Exception {
16       //得到一个 指定算法密钥的密钥生成器
17       KeyGenerator KeyGenerator keyGenerator =KeyGenerator.getInstance(MAC_NAME); 
18       //生成一个密钥
19       SecretKey secretKey =keyGenerator.generateKey();
20       return null;
21       }
22      */
23     
24     /** 
25      * 使用 HMAC-SHA1 签名方法对对encryptText进行签名 
26      * @param encryptText 被签名的字符串 
27      * @param encryptKey  密钥 
28      * @return 
29      * @throws Exception 
30      */  
31     public static byte[] HmacSHA1Encrypt(String encryptText, String encryptKey) throws Exception   
32     {         
33         byte[] data=encryptKey.getBytes(ENCODING);
34         //根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
35         SecretKey secretKey = new SecretKeySpec(data, MAC_NAME); 
36         //生成一个指定 Mac 算法 的 Mac 对象
37         Mac mac = Mac.getInstance(MAC_NAME); 
38         //用给定密钥初始化 Mac 对象
39         mac.init(secretKey);  
40         
41         byte[] text = encryptText.getBytes(ENCODING);  
42         //完成 Mac 操作 
43         return mac.doFinal(text);  
44     }  
45 }

 

原文地址:https://www.cnblogs.com/fishou/p/4159034.html