Administrator
2024-07-15 740de92b22fe7e4742bd0f46e3f57debf8370f2f
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
package com.dy.pipIrrWechat.util;
 
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
 
/**
 * @author ZhuBaoMin
 * @date 2024-07-15 10:19
 * @LastEditTime 2024-07-15 10:19
 * @Description
 */
public class HmacSha256 {
    public static String getSignature(String secretKey, String data) throws NoSuchAlgorithmException, InvalidKeyException {
        // 创建密钥对象
        byte[] keyBytes = secretKey.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "HmacSHA256");
 
        // 创建Mac对象并初始化
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(secretKeySpec);
 
        // 将待加密的数据转换为字节数组
        byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);
 
        // 使用密钥对数据进行加密
        byte[] encryptedBytes = mac.doFinal(dataBytes);
 
        // 将加密后的结果转换为十六进制字符串
        StringBuilder hexString = new StringBuilder();
        for (byte b : encryptedBytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        String hmacSha256 = hexString.toString();
        return hmacSha256;
    }
}