6

我现在正在尝试使用 Java 使用 HMAC-SHA256 对字符串进行编码。匹配由 Python 生成的另一组编码字符串所需的编码字符串hmac.new(mySecret, myPolicy, hashlib.sha256).hexdigest()。我努力了

    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 加密方法相同的结果

hmac.new(mySecret, myPolicy, hashlib.sha256).hexdigest()

因此,我尝试寻找库或与上述 Python 函数类似的东西。有人可以帮帮我吗?

4

1 回答 1

11

你确定你的键和输入是相同的,并且在 java 和 python 中都正确编码了吗?

HMAC-SHA256 在两个平台上的工作方式相同。

爪哇

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
于 2013-07-30T14:12:31.413 回答