gpt4 book ai didi

Java 和 Python 生成不同的 Hmac-SHA256 输出

转载 作者:搜寻专家 更新时间:2023-11-01 03:34:08 27 4
gpt4 key购买 nike

我正尝试在 Python 中生成与在我的 Java 模板中相同的 Hmac-SHA256 签名。但是 Python 脚本生成不同的输出。我找不到我的错误。谁能帮帮我?

Java

public class Main {
public static void main(String[] args) {
String paramString = "teststring";
calculateSignature(hash(paramString));
}

private static byte[] hash(String paramString)
{
MessageDigest localMessageDigest = MessageDigest.getInstance("SHA-256");
localMessageDigest.update(paramString.getBytes("UTF-8"));
byte[] paramByte = localMessageDigest.digest();
System.out.println("Hash: " + DatatypeConverter.printBase64Binary(paramByte));
return paramByte;
}

public static void calculateSignature(byte[] paramArrayOfByte)
{
String Algor = "HmacSHA256";
Mac localMac = Mac.getInstance(Algor);
byte [] key = "secretkey".getBytes();
localMac.init(new SecretKeySpec(key, Algor));
paramArrayOfByte = localMac.doFinal(paramArrayOfByte);
System.out.println("Signature: " + DatatypeConverter.printBase64Binary(paramArrayOfByte));
}
}

Hash: PIcn4BmkK0RGZ6WHtgASUb7K2ruza/7YCHqSwYiC0RE=

Signature: X8V4RA7qaoVGz5K2l61gAXNPuLkAI7NZ9/9d7WnblbA=

python

# -*- coding: utf-8 -*-
import hashlib
import base64
import hmac

secretkey = 'secretkey'
stringToSign = "teststring"

def hash(paramstring):
x = base64.b64encode(hashlib.sha256(paramstring).digest())
print('Hash: ' + x)
return x

def calculate_signature(hashvalue):
x = base64.b64encode(hmac.new(secretkey, hashvalue, hashlib.sha256).digest())
print('Signature: ' + x)

calculate_signature(hash(stringToSign))

Hash: PIcn4BmkK0RGZ6WHtgASUb7K2ruza/7YCHqSwYiC0RE=

Signature: NE8RtuFsOtafWrwDdlzILMgqCDm2huJ9A3IO6iy44Jc=

最佳答案

问题是在 python 代码中你返回 base64 编码但在 java 中你只是将它打印为 base64 编码但没有返回。

尝试:

private static byte[] hash(String paramString)
{
MessageDigest localMessageDigest = MessageDigest.getInstance("SHA-256");
localMessageDigest.update(paramString.getBytes("UTF-8"));
byte[] paramByte = localMessageDigest.digest();
String base64Binary = DatatypeConverter.printBase64Binary(paramByte);
System.out.println("Hash: " + base64Binary);
return base64Binary.getBytes();
}

或者修改python代码为:

def hash(paramstring):
x = hashlib.sha256(paramstring).digest()
return x

关于Java 和 Python 生成不同的 Hmac-SHA256 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36815817/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com