Android (Java) 方法等效于十六进制的 Python HMAC-SHA256 [英] Android (Java) method equivalent to Python HMAC-SHA256 in Hex

查看:105
本文介绍了Android (Java) 方法等效于十六进制的 Python HMAC-SHA256的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Android (Java) 中复制 Python HMAC-SHA256 等效项.Python 表示如下所示,并带有正确的输出:

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

蟒蛇

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

Output
5B5EE08A20DDD645A31384E51AC581A4551E9BE5AC8BF7E690A5527F2B9372CB

但是,我无法使用以下代码在 Java 中获得相同的输出:

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

我相当肯定我的问题是无法编写与 Python 等效的 Java 代码:

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") 

这是因为当我不对 Python 中的十六进制字符串输入执行 binascii.unhexlify 时,我会为两种方法呈现相同的结果.但是,Python HMAC-SHA256 需要 binascii.unhexlify 操作.

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.

我做了大量研究,甚至尝试导入 Python 用于在 Java 中执行 binascii.unhexlify 的方法,但我仍然无法产生相同的结果.在解决此问题时,任何帮助和/或建议都将不胜感激.有人可以帮我吗?

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?

推荐答案

这可能会有所帮助...我已经创建了代码以在 Java 和 Python 中创建哈希并将代码上传到 Github.

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

两个程序在 base64 中创建相同的哈希码.

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

回购网址:https://github.com/AsadShakeel/HMAC-Java-Python 哈希

这篇关于Android (Java) 方法等效于十六进制的 Python HMAC-SHA256的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆