Android (Java) method equivalent to Python HMAC-SHA256 in Hex

ぃ、小莉子 提交于 2019-12-04 14:51:59

问题


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?

来源:https://stackoverflow.com/questions/24554946/android-java-method-equivalent-to-python-hmac-sha256-in-hex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!