【问题标题】:what is keyed-HMAC (Hash Message Authentication Code)什么是 keyed-HMAC(哈希消息验证码)
【发布时间】:2011-04-28 16:00:12
【问题描述】:

什么是keyed-HMAC(哈希消息验证码)?以及如何使用java在Web服务中编写HMAC?

【问题讨论】:

标签: java web-services restful-authentication


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多