Java方法,可以为Hex中的HMAC-SHA256提供与Python方法相同的输出

Tak*_*umi 5 python java hmac

我现在正尝试使用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());
Run Code Online (Sandbox Code Playgroud)

打印出来后,hash,hexB,check和sha256没有提供与下面的Python加密方法相同的结果

hmac.new(mySecret, myPolicy, hashlib.sha256).hexdigest()
Run Code Online (Sandbox Code Playgroud)

所以,我试图寻找类似于上述Python函数的库或其他东西.有人可以帮帮我吗?

Syo*_*yon 10

你确定你的密钥和输入是相同的,并在java和python中正确编码?

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

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
Run Code Online (Sandbox Code Playgroud)

蟒蛇

print hmac.new("1234", "test", hashlib.sha256).hexdigest();

Output
24c4f0295e1bea74f9a5cb5bc40525c8889d11c78c4255808be00defe666671f
Run Code Online (Sandbox Code Playgroud)