puzhibing
2022-08-22 1421f8e9c308c4741cb396309035009393b5b036
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.stylefeng.guns.modular.system.auth;
 
import org.apache.tomcat.util.codec.binary.Base64;
 
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
 
public class HMACSHA1 {
 
    private static final String MAC_NAME = "HmacSHA1";
    private static final String ENCODING = "UTF-8";
 
    /*
     * 展示了一个生成指定算法密钥的过程 初始化HMAC密钥
     * 
     * @return
     * 
     * @throws Exception
     * 
     * public static String initMacKey() throws Exception { //得到一个 指定算法密钥的密钥生成器
     * KeyGenerator KeyGenerator keyGenerator
     * =KeyGenerator.getInstance(MAC_NAME); //生成一个密钥 SecretKey secretKey
     * =keyGenerator.generateKey(); return null; }
     */
 
    /**
     * 使用 HMAC-SHA1 签名方法对对encryptText进行签名
     * 
     * @param encryptText
     *            被签名的字符串
     * @param encryptKey
     *            密钥
     * @return
     * @throws Exception
     */
    public static byte[] HmacSHA1Encrypt(String encryptText, String encryptKey) throws Exception {
        byte[] data = encryptKey.getBytes(ENCODING);
        // 根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
        Mac mac = Mac.getInstance(MAC_NAME);
        SecretKey secretKey = new SecretKeySpec(data, MAC_NAME);
        // 生成一个指定 Mac 算法 的 Mac 对象
        // 用给定密钥初始化 Mac 对象
        mac.init(secretKey);
 
        byte[] text = encryptText.getBytes(ENCODING);
        // 完成 Mac 操作
        return mac.doFinal(text);
    }
 
    public static void main(String[] args) {
 
        String encryptText = "123";
        String encryptKey = "adc";
        try {
            byte[] b = HmacSHA1Encrypt(encryptText, encryptKey);
            String str = HashKit.toHex(b);
            String str2 = new String(Base64.encodeBase64(b));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}