[英]Replicating HMAC from C# to Python
我正在使用由客戶提供的 API,該客戶提供了有關通過 C# 進行授權的示例代碼,但我的公司使用 Python。 他們通過 HMAC 進行授權,並按照他們的示例代碼(在 .net fiddle 上),我終於達到了我們的字節密鑰和字節消息與 C# 調用相匹配的地步。
然而,當我們在他們的代碼中得到這個時:
using (HMACSHA256 sha = new HMACSHA256(secretKeyByteArray))
{
// Sign the request
byte[] signatureBytes = sha.ComputeHash(signature);
我們的等價物在哪里
signature_hmac = hmac.new(
base64.b64decode(secretKey),
bytes(message, "utf8"),
digestmod=hashlib.sha256,
)
他們的signatureBytes
的字節值與我們的signature_hmac.digest()
的字節值不匹配。 如果使用相同的哈希庫,並且輸入的字節值匹配,我們應該得到相同的結果,對吧?
為了確保,當我說字節值匹配時, base64.b64decode(secretKey)
(Python) 的值匹配var secretKeyByteArray = Convert.FromBase64String(secretKey);
(C#)。
為我工作,確保您的輸入數組在兩者上完全相同。 我認為您可能缺少 base64 解碼或以不同方式編碼字符串。
這是我的 2 個測試:
secretKey = "wxyz".encode()
message = "abcd".encode()
signature_hmac = hmac.new(
secretKey,
message,
digestmod=hashlib.sha256,
)
x = signature_hmac.hexdigest()
和 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.