I have a small C# function that I want to use in Python. However Im not sure how to use hashlib to accomplish the same result. The function receives a string an returns the base64 encoding of the sha1 hash of the string:
private string ConvertStringToHash(string word)
{
return Convert.ToBase64String(new SHA1CryptoServiceProvider().ComputeHash(new UnicodeEncoding().GetBytes(word)));
}
I tried this on python but im not getting the same results:
def convert_string_to_hash(word):
m1 = hashlib.sha1()
m1.update(word)
res = m1.digest()
encoded = base64.b64encode(res)
return encoded
Whats the best way to accomplish the same thing in Python?
The difference in the output stems from the encoding you are using:
UnicodeEncoding
encodes the input string (word
) as UTF-16 little endian; andSo, just encode the word
as UTF-16 little endian before hashing:
import hashlib
import base64
def convert_string_to_hash(word):
digest = hashlib.sha1(word.encode('utf-16-le')).digest()
return base64.b64encode(digest)
Also, your Python function can be somewhat shortened.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With