如何在 Java 中将 HMAC 密钥指定为十六进制

How to specify HMAC key as hexadecimal in Java

我能够使用以下代码成功获得 HMAC SHA256:

 public static String getHac(String dataUno,  String keyUno) throws InvalidKeyException, NoSuchAlgorithmException, UnsupportedEncodingException {

         SecretKey secretKey = null;    
         Mac mac = Mac.getInstance("HMACSHA256");

         byte[] keyBytes = keyUno.getBytes("UTF-8");     

         secretKey = new SecretKeySpec(keyBytes,mac.getAlgorithm());

         mac.init(secretKey);   

         byte[] text = dataUno.getBytes("UTF-8");

         System.out.println("Hex encode: " + Hex.encode(keyUno.getBytes()));

         byte[] encodedText = mac.doFinal(text);    
         return new String(Base64.encode(encodedText)).trim();

    }

产生:

HMAC: 9rH0svSCPHdbc6qUhco+nlkt2O7HE0rThV4M9Hbv5aY=

不过,我想得到这个:

HMAC:eVXBY4RZmFQcOHHZ5FMRjDLOJ8vCuVGTjy7cHN7pqfo=

我尝试了 online tool,我的代码和在线工具之间的区别似乎是我使用的是密钥类型的文本。

测试值:

字符串数据 = "5515071604000fAIkwJtkeiA:APA91bH_Pb5xB2lrmKWUst5xRuJ3joVE-sb9KoT0zXZuupIEfdHjii-cODj-JMnjyy7hFJUbIRAre9o2yaCU43KaFDmxKlhJhE36Dw0bZ2VntDUn_Zd1EJBuSyCYiUtmmkHfRvRy3hIb";

字符串键 = "fc67bb2ee0648a72317dcc42f232fc24f3964a9ebac0dfab6cf47521e121dc6e";

getHac("5515071604000fAIkwJtkeiA:APA91bH_Pb5xB2lrmKWUst5xRuJ3joVE-sb9KoT0zXZuupIEfdHjii-cODj-JMnjyy7hFJUbIRAre9o2yaCU43KaFDmxKlhJhE36Dw0bZ2VntDUn_Zd1EJBuSyCYiUtmmkHfRvRy3hIb", "fc67bb2ee0648a72317dcc42f232fc24f3964a9ebac0dfab6cf47521e121dc6e"));

我的方法的执行return

9rH0svSCPHdbc6qUhco+nlkt2O7HE0rThV4M9Hbv5aY= (在线return与所选键类型文本相同的值)

我预计

eVXBY4RZmFQcOHHZ5FMRjDLOJ8vCuVGTjy7cHN7pqfo= (在线returns 相同的值,选择的键类型十六进制)

假设您使用的是 Apache Commons Codec 1.11,请使用以下内容:

byte[] keyBytes = Hex.decodeHex(keyUno);

getHac 方法

您的代码稍作修改后如下所示:

public static String getHac(String dataUno,  String keyUno) 
        throws InvalidKeyException, NoSuchAlgorithmException, UnsupportedEncodingException, DecoderException {

    SecretKey secretKey;
    Mac mac = Mac.getInstance("HMACSHA256");

    byte[] keyBytes = Hex.decodeHex(keyUno);

    secretKey = new SecretKeySpec(keyBytes, mac.getAlgorithm());

    mac.init(secretKey);

    byte[] text = dataUno.getBytes("UTF-8");

    byte[] encodedText = mac.doFinal(text);
    return new String(Base64.encodeBase64(encodedText)).trim();
}

测试

这个Java方法给出了预期的结果:

eVXBY4RZmFQcOHHZ5FMRjDLOJ8vCuVGTjy7cHN7pqfo=