[英]SHA256 Hashing with Utf-8 Encoding C# to Python
I want to convert this c# code to python.我想将此 c# 代码转换为 python。 I want to do SHA256 hashing with utf-8 encoding like c# code.我想使用 utf-8 编码(如 c# 代码)进行 SHA256 散列。 But when I print results, they are different (results are in comment lines).但是当我打印结果时,它们是不同的(结果在注释行中)。 What is the point I miss?我想念的重点是什么?
From:从:
//C# code
string passw = "value123value";
SHA256CryptoServiceProvider sHA256 = new SHA256CryptoServiceProvider();
byte[] array = new byte[32];
byte[] sourceArray = sHA256.ComputeHash(Encoding.UTF8.GetBytes(passw));
Console.WriteLine(Encoding.UTF8.GetString(sourceArray)); //J�Q�XV�@�?VQ�mjGK���2
To:到:
#python code
passw = "value123value"
passw = passw.encode('utf8') #convert unicode string to a byte string
m = hashlib.sha256()
m.update(passw)
print(m.hexdigest()) #0c0a903c967a42750d4a9f51d958569f40ac3f5651816d6a474b1f88ef91ec32
m.hexdigest()
prints the values of the result array as hexadecimal digits.将结果数组的值打印为十六进制数字。 Calling打电话
Encoding.UTF8.GetString(sourceArray)
in C# will not.在 C# 中不会。 You could use你可以用
BitConverter.ToString(sourceArray).Replace("-", "");
to achieve the following output:实现以下输出:
0C0A903C967A42750D4A9F51D958569F40AC3F5651816D6A474B1F88EF91EC32 0C0A903C967A42750D4A9F51D958569F40AC3F5651816D6A474B1F88EF91EC32
See this question for further methods to print the array as hex string.有关将数组打印为十六进制字符串的更多方法,请参阅此问题。
On the other side, in Python you can do it like另一方面,在 Python 中你可以这样做
print(''.join('{:02x}'.format(x) for x in m.digest()))
or other ways like described in this question .或此问题中描述的其他方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.