2011-04-28 78 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); 
    } 
}