悉野小楼

导航

几种语言实现hmac_sha256签名方法

php:

function php_hmac_sha256($secret, $message) {
    $hmac = hash_hmac('sha256', $message, $secret);
    return $hmac;
}

java:

/**
     * 使用HMAC-SHA256算法生成签名
     *
     * @param secret 密钥
     * @param message 消息
     * @return 签名的十六进制字符串
     */
    public static String java_hmac_sha256(String secret, String message) {
        try {
            Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
            SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
            sha256_HMAC.init(secret_key);
            byte[] hash = sha256_HMAC.doFinal(message.getBytes(StandardCharsets.UTF_8));
            return bytesToHex(hash);
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            throw new RuntimeException("Failed to generate HMAC-SHA256 signature", e);
        }
    }

go:

/**
 * 使用HMAC-SHA256算法生成签名
 *
 * @param secret 密钥
 * @param message 消息
 * @return 签名的十六进制字符串
 */
func go_hmac_sha256(secret, message string) string {
    // 创建 HMAC-SHA256 的哈希对象,并使用密钥初始化
    mac := hmac.New(sha256.New, []byte(secret))
    // 写入消息数据
    mac.Write([]byte(message))
    // 计算 HMAC
    sum := mac.Sum(nil)
    // 将字节数组转换为十六进制字符串
    return hex.EncodeToString(sum)
}

 javascript:

<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>
// 使用 CryptoJS 计算 HMAC-SHA256
function hmacSha256(secret, message) {
    const hmac = CryptoJS.HmacSHA256(message, secret);
    return hmac.toString(CryptoJS.enc.Hex); // 转换为十六进制字符串
}

 

posted on 2025-04-24 11:09  悉野  阅读(138)  评论(0)    收藏  举报