Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to base 64 from sha1 Hash in Python

Tags:

python

c#

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?

like image 789
Pablo Estrada Avatar asked Oct 14 '25 12:10

Pablo Estrada


1 Answers

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

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.

like image 105
randomir Avatar answered Oct 17 '25 00:10

randomir