1

I am attempting to replicate the Python HMAC-SHA256 equivalent in Android (Java). The Python representation is shown bellow with the correct output:

Python

print (hmac.new(key = binascii.unhexlify("0123465789"),msg = binascii.unhexlify("ABCDEF"),digestmod=hashlib.sha256).hexdigest()).upper()

Output
5B5EE08A20DDD645A31384E51AC581A4551E9BE5AC8BF7E690A5527F2B9372CB

However, I am unable to get the same output in Java using the code below:

Java

Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKey = new SecretKeySpec("0123465789".getBytes("UTF-8"), "HmacSHA256");      
sha256_HMAC.init(secretKey);
byte[] hash = sha256_HMAC.doFinal("ABCDEF".getBytes("UTF-8"));      
String check = (new String(Hex.encodeHex(hash))).toUpperCase();
System.out.println(check);

Output
46F9FD56BDAE29A803BAD5BC668CB78DA4C54A51E6C031FB3BC2C42855047213

I am fairly positive that my problem is failing to code the Java equivalent of Python's:

key = binascii.unhexlify("0123465789")

&

msg = binascii.unhexlify("ABCDEF") 

This is because when I do not perform the binascii.unhexlify on the Hex-String inputs in Python, I render identical results for both methods. However, the Python HMAC-SHA256 requires the binascii.unhexlify operation.

I have done a lot of research and even attempted to import the method that Python uses to perform the binascii.unhexlify in Java but I am still unable to produce identical results. Any help and/or advise would be more than appreciated in solving this issue. Can anybody help me out?

  • You are hex-decoding key and message in your python code, so in Java instead of using `"0123465789".getBytes("UTF-8")` you obviously need to [hex-decode strings](http://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using-java) that represent the key and message. – Oleg Estekhin Jul 04 '14 at 05:58
  • possible duplicate of [Python HMAC-SHA1 vs Java HMAC-SHA1 different results](http://stackoverflow.com/questions/13019598/python-hmac-sha1-vs-java-hmac-sha1-different-results), probably not a good choice for a duplicate but the gist of the problem is the same - if hex is used in one language, use hex encoding in another language in appropriate places too. – Oleg Estekhin Jul 04 '14 at 06:05

1 Answers1

0

This may help... I've created code to create the hash in Java and Python and uploaded the code to Github.

Both of the programs creating the same hash code in base64.

Repo URL: https://github.com/AsadShakeel/HMAC-Java-Python-Hashing

Asad Shakeel
  • 1,949
  • 1
  • 23
  • 29