简体   繁体   English

将 HMAC 从 C# 复制到 Python

[英]Replicating HMAC from C# to Python

I'm working with an API provided by a client, who provided sample code on authorizing via C#, but my company works in Python.我正在使用由客户提供的 API,该客户提供了有关通过 C# 进行授权的示例代码,但我的公司使用 Python。 They authorize via HMAC, and following their sample code (on .net fiddle), I finally got to the point where our byte key and byte message match those of the C# call.他们通过 HMAC 进行授权,并按照他们的示例代码(在 .net fiddle 上),我终于达到了我们的字节密钥和字节消息与 C# 调用相匹配的地步。

However, when we get to this in their code:然而,当我们在他们的代码中得到这个时:

using (HMACSHA256 sha = new HMACSHA256(secretKeyByteArray))
    {
        // Sign the request
        byte[] signatureBytes = sha.ComputeHash(signature);

Where our equivalent is我们的等价物在哪里

signature_hmac = hmac.new(
    base64.b64decode(secretKey),
    bytes(message, "utf8"),
    digestmod=hashlib.sha256,
)

The byte value of their signatureBytes doesn't match with the byte value of our signature_hmac.digest() .他们的signatureBytes的字节值与我们的signature_hmac.digest()的字节值不匹配。 If using the same hashing libraries, and the byte values of the inputs match, we should get the same result, right?如果使用相同的哈希库,并且输入的字节值匹配,我们应该得到相同的结果,对吧?

To make sure, when I say byte values match, the value of base64.b64decode(secretKey) (Python) matched var secretKeyByteArray = Convert.FromBase64String(secretKey);为了确保,当我说字节值匹配时, base64.b64decode(secretKey) (Python) 的值匹配var secretKeyByteArray = Convert.FromBase64String(secretKey); (C#). (C#)。

Worked for me, make sure your input arrays are EXACTLY the same on both.为我工作,确保您的输入数组在两者上完全相同。 I think you might be missing a base64 decode or encoding the strings differently.我认为您可能缺少 base64 解码或以不同方式编码字符串。

Here's my 2 tests:这是我的 2 个测试:

secretKey = "wxyz".encode()
message = "abcd".encode()
signature_hmac = hmac.new(
    secretKey,
    message,
    digestmod=hashlib.sha256,
)
x = signature_hmac.hexdigest()

and C#和 C#

byte[] signatureBytes;
byte[] secretKeyByteArray = Encoding.UTF8.GetBytes("wxyz");
byte[] signature = Encoding.UTF8.GetBytes("abcd");
using (HMACSHA256 sha = new HMACSHA256(secretKeyByteArray))
{
    signatureBytes = sha.ComputeHash(signature);
};

string x = Convert.ToHexString(signatureBytes);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM