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

时间:2019-01-03 22:57:47

标签: java encryption key sha256 hmacsha1

我可以使用以下代码成功获取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-JMnjyy7hFJUbIRAre9o2yaCU43YFyZyHyByZhZyKnZyKnZyZyZhZyZhZhZnTyZhZnTyZhZeZhZeKnZhZeJ)

字符串键=“ fc67bb2ee0648a72317dcc42f232fc24f3964a9ebac0dfab6cf47521e121dc6e”;

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

执行我的方法返回

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

我期望

eVXBY4RZmFQcOHHZ5FMRjDLOJ8vCuVGTjy7cHN7pqfo = (在线返回的值与选定的十六进制键类型相同)

1 个答案:

答案 0 :(得分:2)

假设您正在使用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=