java 实现php hashhmac
在 Java 中实现 PHP 的 hash_hmac
要在 Java 中实现 PHP 的 hash_hmac 功能,可以使用 Java 的加密库来生成 HMAC(Hash-based Message Authentication Code)。以下是一个完整的实现方法。
导入必要的库
确保项目中包含 Java 的标准加密库:

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
实现 HMAC 生成
以下是一个通用的方法,用于生成 HMAC,支持多种哈希算法(如 SHA-256、SHA-1、MD5 等):
public static String hashHmac(String algorithm, String data, String key) {
try {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), algorithm);
Mac mac = Mac.getInstance(algorithm);
mac.init(secretKey);
byte[] rawHmac = mac.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(rawHmac);
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new RuntimeException("Failed to generate HMAC", e);
}
}
调用示例
如果需要生成 SHA-256 的 HMAC:

String data = "message";
String key = "secret";
String hmacSha256 = hashHmac("HmacSHA256", data, key);
System.out.println("HMAC-SHA256: " + hmacSha256);
如果需要生成十六进制格式的 HMAC(类似于 PHP 的 hash_hmac 默认输出):
public static String hashHmacHex(String algorithm, String data, String key) {
try {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), algorithm);
Mac mac = Mac.getInstance(algorithm);
mac.init(secretKey);
byte[] rawHmac = mac.doFinal(data.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte b : rawHmac) {
hexString.append(String.format("%02x", b));
}
return hexString.toString();
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new RuntimeException("Failed to generate HMAC", e);
}
}
支持的算法列表
Java 支持的 HMAC 算法包括:
HmacSHA256HmacSHA1HmacSHA512HmacMD5
根据需求选择合适的算法即可。






