Java中的SHA256 HMAC算法介绍及示例

简介

SHA256 HMAC(Hash-based Message Authentication Code)是一种基于哈希函数的消息认证码算法,用于验证消息的完整性和真实性。它使用SHA256哈希函数和密钥来生成一个固定长度的摘要,用于验证数据在传输过程中是否被篡改。

在Java中,可以使用javax.crypto包下的Mac类来实现SHA256 HMAC算法。

代码示例

下面是一个使用SHA256 HMAC算法生成消息摘要的示例代码:

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class SHA256HmacExample {

    public static byte[] calculateHmac(String message, String key) throws NoSuchAlgorithmException, InvalidKeyException {
        Mac hmac = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        hmac.init(secretKey);
        return hmac.doFinal(message.getBytes(StandardCharsets.UTF_8));
    }

    public static void main(String[] args) {
        try {
            String message = "Hello, world!";
            String key = "secret_key";

            byte[] hmacResult = calculateHmac(message, key);

            StringBuilder sb = new StringBuilder();
            for (byte b : hmacResult) {
                sb.append(String.format("%02x", b));
            }
            String hmacHex = sb.toString();

            System.out.println("HMAC Hex: " + hmacHex);
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            e.printStackTrace();
        }
    }
}

原理解析

  1. 导入相应的Java包:
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
  1. 创建一个calculateHmac方法用于计算HMAC:
public static byte[] calculateHmac(String message, String key) throws NoSuchAlgorithmException, InvalidKeyException {
    Mac hmac = Mac.getInstance("HmacSHA256");
    SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
    hmac.init(secretKey);
    return hmac.doFinal(message.getBytes(StandardCharsets.UTF_8));
}
  1. 在main方法中调用calculateHmac方法,并将结果转换为十六进制字符串:
public static void main(String[] args) {
    try {
        String message = "Hello, world!";
        String key = "secret_key";

        byte[] hmacResult = calculateHmac(message, key);

        StringBuilder sb = new StringBuilder();
        for (byte b : hmacResult) {
            sb.append(String.format("%02x", b));
        }
        String hmacHex = sb.toString();

        System.out.println("HMAC Hex: " + hmacHex);
    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
        e.printStackTrace();
    }
}

结论

SHA256 HMAC算法是一种用于验证消息完整性和真实性的方法。Java中提供了Mac类来实现SHA256 HMAC算法。通过计算消息的HMAC摘要,可以确保数据在传输过程中没有被篡改。以上示例代码演示了如何在Java中使用SHA256 HMAC算法生成消息摘要。