Java方法,它可以为HMACSHA256提供与Python方法相同的十六进制输出

2024-05-13 22:37:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在正尝试使用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加密方法相同的结果

^{pr2}$

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


Tags: 字符串编码newsecretmachashbytehmac
1条回答
网友
1楼 · 发布于 2024-05-13 22:37:10

您确定您的键和输入在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

^{pr2}$

相关问题 更多 >