输出的哈希值长度为 160 位。
接收方重新计算所接收消息的哈希值,并检查计算所得的 HMAC 是否与传送的 HMAC 匹配。
因此,如果原始的哈希值与计算得出的哈希值相匹配,则消息通过身份验证。
它将从任意长度的字符串生成 28位长的字符串。
- import java.security.InvalidKeyException;
- import java.security.NoSuchAlgorithmException;
-
- import javax.crypto.Mac;
- import javax.crypto.spec.SecretKeySpec;
-
- import org.apache.commons.codec.binary.Base64;
-
-
-
-
-
-
-
- public class HMAC_SHA1 {
-
- private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
-
-
-
-
-
-
-
-
-
-
-
- public static String genHMAC(String data, String key) {
- byte[] result = null;
- try {
-
- SecretKeySpec signinKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
-
- Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
-
- mac.init(signinKey);
-
- byte[] rawHmac = mac.doFinal(data.getBytes());
- result = Base64.encodeBase64(rawHmac);
-
- } catch (NoSuchAlgorithmException e) {
- System.err.println(e.getMessage());
- } catch (InvalidKeyException e) {
- System.err.println(e.getMessage());
- }
- if (null != result) {
- return new String(result);
- } else {
- return null;
- }
- }
-
-
-
-
- public static void main(String[] args) {
- String genHMAC = genHMAC("111", "2222");
- System.out.println(genHMAC.length());
- System.out.println(genHMAC);
- }
- }