HmacSHA256验证
时间: 2023-07-25 09:42:22 浏览: 93
delphi访问https参数验证 HMAC_SHA256 控件包
如果你有一个HmacSHA256散列值和原始消息,可以使用以下Java代码验证散列值是否正确:
```java
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
public class HmacSHA256Demo {
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException {
String message = "hello world";
String key = "secret_key";
String hash = "2hFvQMOhZ5JJ9Ut8J5R9XK4qzvNz59v2N9KsK8eJGv8=";
Mac sha256Hmac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "HmacSHA256");
sha256Hmac.init(secretKey);
byte[] hashBytes = sha256Hmac.doFinal(message.getBytes());
String calculatedHash = Base64.getEncoder().encodeToString(hashBytes);
System.out.println("Message: " + message);
System.out.println("Expected HmacSHA256 hash: " + hash);
System.out.println("Calculated HmacSHA256 hash: " + calculatedHash);
if (hash.equals(calculatedHash)) {
System.out.println("HmacSHA256 hash matches");
} else {
System.out.println("HmacSHA256 hash does not match");
}
}
}
```
这段代码使用了Java的加密库javax.crypto来计算HmacSHA256散列值,并使用Base64编码将结果输出。然后,它将计算出的散列值与给定的散列值进行比较,如果它们匹配,则散列值是正确的。
阅读全文