问题描述
我现在正尝试使用Java使用HMAC-SHA256对字符串进行编码.匹配由Python使用hmac.new(mySecret, myPolicy, hashlib.sha256).hexdigest()
生成的另一组编码字符串所需的编码字符串.我尝试过
I am now trying to encode the string using HMAC-SHA256 using Java. The encoded string required to match another set of encoded string generated by Python using hmac.new(mySecret, myPolicy, hashlib.sha256).hexdigest()
. I have tried
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
sha256_HMAC.init(secretKey);
byte[] hash = sha256_HMAC.doFinal(policy.getBytes());
byte[] hexB = new Hex().encode(hash);
String check = Hex.encodeHexString(hash);
String sha256 = DigestUtils.sha256Hex(secret.getBytes());
在我将它们打印出来后,hash,hexB,check和sha256不能提供与以下Python加密方法相同的结果
after I print them out, hash, hexB, check and sha256 didn't provide the same result as the following Python encryption method
hmac.new(mySecret, myPolicy, hashlib.sha256).hexdigest()
因此,我尝试寻找该库或类似上述Python函数的库.有人可以帮我吗?
So, I have try to looking for the library or something that work similar to the above Python function. Can anybody help me out?
推荐答案
您确定您的键和输入是相同的,并且在Java和python中都正确编码吗?
Are you sure your key and input are identical and correctly encoded in both java and python?
HMAC-SHA256在两个平台上均相同.
HMAC-SHA256 works the same on both platforms.
Java
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKey = new SecretKeySpec("1234".getBytes(), "HmacSHA256");
sha256_HMAC.init(secretKey);
byte[] hash = sha256_HMAC.doFinal("test".getBytes());
String check = Hex.encodeHexString(hash);
System.out.println(new String(check));
Output
24c4f0295e1bea74f9a5cb5bc40525c8889d11c78c4255808be00defe666671f
Python
print hmac.new("1234", "test", hashlib.sha256).hexdigest();
Output
24c4f0295e1bea74f9a5cb5bc40525c8889d11c78c4255808be00defe666671f
这篇关于Java方法可以为Hex中的HMAC-SHA256提供与Python方法相同的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!