【问题标题】:SHA256 Hashing with Utf-8 Encoding C# to Python使用 Utf-8 将 C# 编码为 Python 的 SHA256 散列
【发布时间】:2021-02-18 06:56:59
【问题描述】:

我想将此 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

【问题讨论】:

  • 在 C# 中将哈希 (sourceArray) 转换为十六进制字符串,而不是尝试将其转换为 UTF-8 字符串(这样做没有意义,哈希不是文本):@987654321 @
  • Encoding.UTF8.GetString(sourceArray) is not well defined 如果 sourceArray 实际上不是 UTF8(它不在这里)

标签: python c# encoding hash sha256


【解决方案1】:
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中描述的其他方式。

【讨论】:

    猜你喜欢
    • 2019-03-31
    • 2013-06-02
    • 1970-01-01
    • 2015-08-06
    • 1970-01-01
    • 1970-01-01
    • 2014-01-24
    • 2012-04-24
    • 2015-11-08
    相关资源
    最近更新 更多