zhitong.yu
2024-05-11 b72f8f8d58417eb6fb29672d8ac17cfafa46775c
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
package com.hxzk.util;
 
import org.bouncycastle.crypto.RuntimeCryptoException;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
 
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.security.Security;
import java.text.ParseException;
import java.util.Base64;
 
public class HmacSHA256 {
    /**
     * @param content 加密内容
     * @param secret  加密key
     *                使用 HMAC-SHA256 以 secret为密钥(字符串形式,非原始二进制),以 content为消息,计算消息摘要,再进行base64编码处理,得到 signature
     * @return
     */
    public static String encrytSHA256(String content, String secret) {
 
        try {
            Security.addProvider(new BouncyCastleProvider());
            SecretKey secretKey = new SecretKeySpec(secret.getBytes("UTF8"), "HmacSHA256");
            Mac mac = Mac.getInstance(secretKey.getAlgorithm());
            mac.init(secretKey);
            byte[] digest = mac.doFinal(content.getBytes("UTF-8"));
            //return new HexBinaryAdapter().marshal(digest).toLowerCase();
            // .toLowerCase()小写
            // .toUpperCase();大写
 
            //加密后用base64再加密
            String signature = Base64.getEncoder().encodeToString(digest);
        } catch (Exception e) {
            throw new RuntimeCryptoException("加密异常");
        }
 
        return content;
    }
    public static void main(String[] args) throws ParseException, IOException {
        System.out.println(encrytSHA256("加密内容", "key"));
    }
}