what is keyed-HMAC (Hash Message Authentication Code)? An开发者_运维百科d how to write HMAC in web service using java?
An HMAC is a digest used to verify the authenticity of a message. Unlike, say an md5 signature, it's generated using a secret key known only to you and the receiving party so that it shouldn't be possible to forge by a third party.
In order to generate one, you'll need to make use of some java.security classes. Try this:
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);
}
}
精彩评论