java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java hmacsha1加密算法

Java实现hmacsha1加密算法的完整代码

作者:考虑考虑

HMAC是一种利用加密哈希函数结合密钥来验证消息完整性和真实性的机制,HMAC-SHA1 使用 SHA-1 作为底层哈希函数,输出长度为 160 位(20 字节) 的摘要,下面我们就来看看如何使用Java实现hmacsha1加密算法吧

前言

Java本身就自带加密算法实现,实现hmacsha1加密算法,可以利用本身自带的方法

什么是 HMAC-SHA1?

HMAC(Hash‑based Message Authentication Code,基于哈希的消息认证码)是一种利用加密哈希函数结合密钥来验证消息完整性和真实性的机制。HMAC-SHA1 使用 SHA-1 作为底层哈希函数,输出长度为 160 位(20 字节) 的摘要。

核心特点:

典型应用:

hmacsha1加密算法实现

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&ee050d34cabc|sdkappid=20250616;random=0";
        String deviceSecret = "dARYgMURsw0pAV1w";
        // 1. 将签名类型标识改为 hmacsha1
        String signatureType = "hmacsha1"; 

        try {
            // 2. 将算法实例改为 HmacSHA1
            Mac mac = Mac.getInstance("HmacSHA1");
            SecretKeySpec secretKeySpec = new SecretKeySpec(
                    deviceSecret.getBytes(StandardCharsets.UTF_8), 
                    "HmacSHA1" // 3. 密钥规范也需同步改为 HmacSHA1
            );
            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 实现 HMAC-SHA1 的核心步骤

Java 标准库提供了 javax.crypto.Mac 类,可以方便地实现 HMAC 算法,无需任何第三方依赖。

1. 算法名称

"HmacSHA1"(注意大小写)。

2. 核心 API

3. 输出格式

原始结果为 byte[](20 字节),通常转换为十六进制字符串或 Base64 字符串以便传输。

完整代码示例

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class HMACSHA1Example {
    /**
     * 计算 HMAC-SHA1 摘要,返回十六进制字符串
     */
    public static String hmacSha1Hex(String key, String message) throws Exception {
        byte[] hmacBytes = hmacSha1(key, message);
        return bytesToHex(hmacBytes);
    }
    /**
     * 计算 HMAC-SHA1 摘要,返回 Base64 字符串
     */
    public static String hmacSha1Base64(String key, String message) throws Exception {
        byte[] hmacBytes = hmacSha1(key, message);
        return Base64.getEncoder().encodeToString(hmacBytes);
    }
    /**
     * 计算 HMAC-SHA1 摘要,返回原始字节数组
     */
    public static byte[] hmacSha1(String key, String message) throws Exception {
        // 1. 获取 Mac 实例
        Mac mac = Mac.getInstance("HmacSHA1");
        // 2. 创建密钥规范(使用 UTF-8 编码)
        SecretKeySpec keySpec = new SecretKeySpec(
            key.getBytes(StandardCharsets.UTF_8), 
            "HmacSHA1"
        );
        // 3. 初始化
        mac.init(keySpec);
        // 4. 执行计算
        return mac.doFinal(message.getBytes(StandardCharsets.UTF_8));
    }
    /**
     * 字节数组转十六进制(小写)
     */
    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b & 0xff));
        }
        return sb.toString();
    }
    // 测试
    public static void main(String[] args) throws Exception {
        String key = "secret_key";
        String message = "Hello, HMAC-SHA1!";
        byte[] raw = hmacSha1(key, message);
        String hex = hmacSha1Hex(key, message);
        String base64 = hmacSha1Base64(key, message);
        System.out.println("原始字节长度: " + raw.length);   // 20
        System.out.println("十六进制: " + hex);              // 例如:c2e7b7e5...
        System.out.println("Base64: " + base64);            // 例如:wue35...
    }
}

进阶用法:增量更新(流式处理)

如果消息较大,可以分块多次调用 update(),最后再调用 doFinal() 获取最终结果。

public static byte[] hmacSha1Incremental(String key, String[] parts) throws Exception {
    Mac mac = Mac.getInstance("HmacSHA1");
    SecretKeySpec keySpec = new SecretKeySpec(
        key.getBytes(StandardCharsets.UTF_8), 
        "HmacSHA1"
    );
    mac.init(keySpec);
    for (String part : parts) {
        mac.update(part.getBytes(StandardCharsets.UTF_8));
    }
    return mac.doFinal(); // 无参数,返回前面所有 update 的总和
}

总结

Java本身就自带加密算法实现,实现hmacsha1加密算法,可以利用本身自带的方法

到此这篇关于Java实现hmacsha1加密算法的完整代码的文章就介绍到这了,更多相关Java hmacsha1加密算法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文