[英]HMAC sha256 returning different values in c# than python
I need to port some python code into c# and I'm having some trouble with this line: 我需要将一些python代码移植到c#中,这行遇到了一些麻烦:
Python 蟒蛇
hmac.new(key, message,digestmod=hashlib.sha256).digest()
C# C#
HMACSHA256 hm = new HMACSHA256(key);
byte[] result = hm.ComputeHash(enc.GetBytes(message));
Why am I getting a different result in C# when key and message are the same (checked byte-by-byte) ? 当键和消息相同(逐字节检查)时,为什么在C#中得到不同的结果?
You can get different hashes for the same message if you use different encodings when converting the message into a byte array. 如果在将消息转换为字节数组时使用不同的编码,则可以为同一消息获得不同的哈希值。 It is not clear which encoding you are using, but the point is that they should match. 目前尚不清楚您使用的是哪种编码,但关键是它们应该匹配。
For example: 例如:
hmac.new("mykey", "mymessage",digestmod=hashlib.sha256).digest()
gTM3eMvH4WsjwCGzp4gZNV5a62dEcWw/gjTMPngjJpQ= gTM3eMvH4WsjwCGzp4gZNV5a62dEcWw / gjTMPngjJpQ =
In C# you get different results depending on your 'enc' variable. 在C#中,根据您的'enc'变量,您将获得不同的结果。
Encoding enc = Encoding.GetEncoding("ASCII");
gTM3eMvH4WsjwCGzp4gZNV5a62dEcWw/gjTMPngjJpQ= gTM3eMvH4WsjwCGzp4gZNV5a62dEcWw / gjTMPngjJpQ =
Encoding enc = Encoding.GetEncoding("Unicode");
2wqHPyE5oiI3ukxOaKo9ao6AN8fcwjgdDInBHTXTwGQ= 2wqHPyE5oiI3ukxOaKo9ao6AN8fcwjgdDInBHTXTwGQ =
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.