什么是keyed-HMAC(哈希消息认证码)?如何在web服务中使用java编写HMAC ?
HMAC是用来验证消息真实性的摘要。与md5签名不同,它是使用只有您和接收方知道的密钥生成的,因此第三方不可能伪造它。
为了生成一个,需要使用一些java。安全类。试试这个:
public byte[] generateHMac(String secretKey, String data, String algorithm /* e.g. "HmacSHA256" */) {
SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes(), algorithm);
try {
Mac mac = Mac.getInstance(algorithm);
mac.init(signingKey);
return mac.doFinal(data.getBytes());
}
catch(InvalidKeyException e) {
throw new IllegalArgumentException("invalid secret key provided (key not printed for security reasons!)");
}
catch(NoSuchAlgorithmException e) {
throw new IllegalStateException("the system doesn't support algorithm " + algorithm, e);
}
}