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
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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.