SHA256 散列与 Utf-8 编码 C# 到 Python

SHA256 Hashing with Utf-8 Encoding C# to Python

我想将此 c# 代码转换为 python。我想像 c# 代码一样使用 utf-8 编码进行 SHA256 哈希。但是当我打印结果时,它们是不同的(结果在注释行中)。我错过了什么?

发件人:

    //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

收件人:

    #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()

将结果数组的值打印为十六进制数字。打电话

Encoding.UTF8.GetString(sourceArray)

在 C# 中不会。你可以使用

BitConverter.ToString(sourceArray).Replace("-", "");

实现如下输出:

0C0A903C967A42750D4A9F51D958569F40AC3F5651816D6A474B1F88EF91EC32

有关将数组打印为十六进制字符串的更多方法,请参阅 this question

另一方面,在Python你可以像

那样做
print(''.join('{:02x}'.format(x) for x in m.digest()))

this question中所述的其他方式。