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
2
  • 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): stackoverflow.com/questions/311165/… Commented Nov 5, 2020 at 14:46
  • 1
    Encoding.UTF8.GetString(sourceArray) is not well defined if the sourceArray is not actually UTF8 (and it isn't here) Commented Nov 5, 2020 at 16:28

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.