Convert string to base 64 from sha1 Hash in Python

Viewed 2844

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?

2 Answers

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())
Related