【发布时间】:2011-04-28 16:00:12
【问题描述】:
什么是keyed-HMAC(哈希消息验证码)?以及如何使用java在Web服务中编写HMAC?
【问题讨论】:
-
对于您问题的第一部分,请咨询en.wikipedia.org/wiki/Message_authentication_code
标签: java web-services restful-authentication
什么是keyed-HMAC(哈希消息验证码)?以及如何使用java在Web服务中编写HMAC?
【问题讨论】:
标签: java web-services restful-authentication
HMAC 是用于验证消息真实性的摘要。不像 md5 签名,它是使用只有您和接收方知道的密钥生成的,因此它不应该被第三方伪造。
为了生成一个,您需要使用一些 java.security 类。试试这个:
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);
}
}
【讨论】: