简体   繁体   English

Python hmac 在 c#

[英]Python hmac in c#

This is the python code which I have to convert in c#这是我必须在 c# 中转换的 python 代码

   ms = "ninoingfbf"
    key = "AgQGCAoMDhASFA=="
    h = hmac.new(key.encode('utf-8'), ms.encode('utf-8'),
     hashlib.sha256).hexdigest().lower()
    print( h )

I was trying the below c# code, but I am getting different results我正在尝试下面的 c# 代码,但我得到了不同的结果

 string msg = "ninoingfbf";
  string keystring = "AgQGCAoMDhASFA==";
  byte[] key = Convert.FromBase64String(keystring);
  HMACSHA256 hmac = new(key);
  byte[] hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(msg));
  var j = BitConverter.ToString(hash).Replace("-", "").ToLower();
   return Ok(j);

Python output = "10d46c65b51ddbb1f3346dca71ca30f139a473dece78dc567f404fdc4ee49e51" Python output = "10d46c65b51ddbb1f3346dca71ca30f139a473dece78dc567f404fdc4ee49e51"

c# output = "2980906b9e1933357db6fc6b791d2d43564555a949667cc9525eff037466add0" c# output = "2980906b9e1933357db6fc6b791d2d43564555a949667cc9525eff037466add0"

The Python code is wrong. Python 代码错误。 It doesn't decode the BASE64 key but uses it as if it was the actual key.它不会解码 BASE64 密钥,而是将其用作实际密钥。 The key must be decoded using the base64 library, not encoded as UTF-8.密钥必须使用base64库解码,而不是编码为 UTF-8。

Strings in Python3 are Unicode and the default encoding is utf-8 , so there's no need to explicitly specify it. Python3 中的字符串为 Unicode ,默认编码为utf-8 ,因此无需显式指定。

The following code returns the same hash as the C# code:以下代码返回与 C# 代码相同的 hash:

import base64
import hash
import hashlib

ms = "ninoingfbf"
key = "AgQGCAoMDhASFA=="

h=hmac.new(base64.b64decode(key),ms.encode(),hashlib.sha256)

print (h.hexdigest())

This returns这返回

2980906b9e1933357db6fc6b791d2d43564555a949667cc9525eff037466add0

Which is identical to the C# output这与 C# output 相同

2980906b9e1933357db6fc6b791d2d43564555a949667cc9525eff037466add0

.NET 5 added a Convert.ToHexString method, so the C# code becomes: .NET 5 增加了一个Convert.ToHexString方法,所以 C# 代码变为:

using System;
using System.Security.Cryptography;
using System.Text;

var msg = "ninoingfbf";
var key = "AgQGCAoMDhASFA==";

HMACSHA256 hmac = new(Convert.FromBase64String(key));
var h = hmac.ComputeHash(Encoding.UTF8.GetBytes(msg));

Console.WriteLine(Convert.ToHexString(h).ToLower());

If you want to save the hash text for comparison you can get rid of ToLower() and use a case-insensitive comparison.如果您想保存 hash 文本进行比较,您可以去掉ToLower()并使用不区分大小写的比较。 In C# you can use one of the String.Compare overloads that ignores case, eg:在 C# 中,您可以使用忽略大小写的String.Compare重载之一,例如:

var areEqual=String.Compare(hash1,hash2,true);

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

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