2011-04-28 44 views
0

什么是密钥-HMAC(散列消息认证码)?以及如何在使用java的web服务中编写HMAC?什么是密钥-HMAC(散列消息认证码)

+0

对于你的问题的第一部分,constult http://en.wikipedia.org/wiki/Message_authentication_code – 2011-04-28 08:03:20

回答

5

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