How to specify HMAC key as hexadecimal in Java

I'm able to successfully get a HMAC SHA256 using the following code:

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

    }

which yields:

HMAC: 9rH0svSCPHdbc6qUhco+nlkt2O7HE0rThV4M9Hbv5aY=

However, i would like getting this:

HMAC:eVXBY4RZmFQcOHHZ5FMRjDLOJ8vCuVGTjy7cHN7pqfo=

I tried an online tool and it appears that the difference between my code and online tool is that I am working with a text in the key type.

Test values:

String data = "5515071604000fAIkwJtkeiA:APA91bH_Pb5xB2lrmKWUst5xRuJ3joVE-sb9KoT0zXZuupIEfdHjii-cODj-JMnjyy7hFJUbIRAre9o2yaCU43KaFDmxKlhJhE36Dw0bZ2VntDUn_Zd1EJBuSyCYiUtmmkHfRvRy3hIb";

String key = "fc67bb2ee0648a72317dcc42f232fc24f3964a9ebac0dfab6cf47521e121dc6e";

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

the execution of my method return

9rH0svSCPHdbc6qUhco+nlkt2O7HE0rThV4M9Hbv5aY= (the online returns the same value with key type text selected)

and i expected

eVXBY4RZmFQcOHHZ5FMRjDLOJ8vCuVGTjy7cHN7pqfo= (the online returns the same value with key type hex selected)

Upvotes: 0

Views: 3018

Answers (1)

Stephan Schlecht
Stephan Schlecht

Reputation: 27106

Assuming that you are using Apache Commons Codec 1.11, use the following:

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

getHac Method

You code just slightly modified looks like this then:

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

Test

This Java method gives then expected result:

eVXBY4RZmFQcOHHZ5FMRjDLOJ8vCuVGTjy7cHN7pqfo=

Upvotes: 4

Related Questions