开发者

what is keyed-HMAC (Hash Message Authentication Code)

开发者 https://www.devze.com 2023-03-01 18:41 出处:网络
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 md

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);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号