HmacSHA256是一种基于SHA-256哈希函数的消息认证码(MAC)算法。它结合了哈希函数和密钥,用于验证数据的完整性和真实性。“Hmac"代表"Hash-based Message Authentication Code”,即基于哈希的消息认证码。
private static final String ALGORITHM = "HmacSHA256";
public static boolean valid(String message, String secret, String signature) {
return signature != null && signature.equals(sign(message, secret));
}
public static String sign(String message, String secret) {
try {
Mac hmac = Mac.getInstance(ALGORITHM);
SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), ALGORITHM);
hmac.init(secret_key);
byte[] bytes = hmac.doFinal(message.getBytes());
return byteArrayToHexString(bytes);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
private static String byteArrayToHexString(byte[] bytes) {
return Base64.getEncoder().encodeToString(bytes);
}
测试代码
public static void main(String[] args) {
String secret = "secret";
String msg = "test123";
String sign = sign(msg, secret);
boolean flag = valid(msg, secret, sign);
System.out.println(flag);
}