Convert String To Base 64 From Sha1 Hash In Python
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
Solution 1:
The difference in the output stems from the encoding you are using:
- in your C# code,
UnicodeEncoding
encodes the input string (word
) as UTF-16 little endian; and - in your Python code, you're not even handling Unicode strings (they must be encoded as some bytes)
So, just encode the word
as UTF-16 little endian before hashing:
import hashlib
import base64
defconvert_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.
Solution 2:
The following worked for me for storing in LDAP. Hex matched, but it was that base64 encode that brought it over the line - python3.
newSaUserPassword = "{SHA256}" + \
base64.b64encode(hashlib.sha256(options.newSaUserPassword.encode("utf-8")).digest())
Post a Comment for "Convert String To Base 64 From Sha1 Hash In Python"