1

I want to convert this c# code to python. I want to do SHA256 hashing with utf-8 encoding like c# code. 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
Max Xapi
  • 750
  • 8
  • 22
phileoseda
  • 292
  • 1
  • 6
  • 29
  • 2
    In C# convert the hash (sourceArray) to a hex string instead of trying to convert it to a UTF-8 string (there is no point in doing that, the hash is not text): https://stackoverflow.com/questions/311165/how-do-you-convert-a-byte-array-to-a-hexadecimal-string-and-vice-versa – Alex K. Nov 05 '20 at 14:46
  • 1
    `Encoding.UTF8.GetString(sourceArray)` is **not well defined** if the `sourceArray` is not actually UTF8 (and it isn't here) – Marc Gravell Nov 05 '20 at 16:28

1 Answers1

3
m.hexdigest()

prints the values of the result array as hexadecimal digits. Calling

Encoding.UTF8.GetString(sourceArray)

in C# will not. You could use

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

to achieve the following output:

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

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

or other ways like described in this question.

Fruchtzwerg
  • 10,999
  • 12
  • 40
  • 49