Java实现hmacsha256加密算法

35 阅读1分钟

前言

Java自带hmacsha256算法

hmacsha256实现

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class SignatureGenerator {
    public static void main(String[] args) {
        String username = "tIsMUhEc0tp&ee050d34cab2|sdkappid=20250616;random=0";
        String deviceSecret = "dARYgMURsw0pAV1w";
        // 1. 将签名类型标识改为 hmacsha256
        String signatureType = "hmacsha256"; 

        try {
            // 2. 将算法实例改为 HmacSHA256
            Mac mac = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKeySpec = new SecretKeySpec(
                    deviceSecret.getBytes(StandardCharsets.UTF_8), 
                    "HmacSHA256" // 3. 密钥规范也需同步改为 HmacSHA256
            );
            mac.init(secretKeySpec);
            byte[] hmacBytes = mac.doFinal(username.getBytes(StandardCharsets.UTF_8));

            // 使用标准 Base64 编码
            String signature = Base64.getEncoder().encodeToString(hmacBytes);

            // 拼接 password
            String password = signature + ";" + signatureType;
            System.out.println("Password: " + password);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

总结

Java实现hmacsha256加密算法,可以用它实现加密算法