Search code examples
pythonhashsha1

Convert PHP to Python


I need help converting the following PHP to python

$plaintext = "MyPassword";
$utf_text = mb_convert_encoding( $plaintext, 'UTF-16LE' );
$sha1_text = sha1( $utf_text, true );
$base64_text = base64_encode( $sha1_text );
echo $base64_text; //ouput = QEy4TXy9dNgleLq+IEcjsQDYm0A=
  1. Convert the string to UTF16LE
  2. Hash the output of 1. using SHA1
  3. Encode the output of 2. using base64 encoding.

Im trying hashlib.sha1 but its not working. Maybe due to this, maybe encodings. Can anyone help


Solution

  • Your PHP code encodes the password to UTF16, little endian; if your password value is a unicode value, that works just fine in Python:

    >>> import hashlib
    >>> plaintext = u"MyPassword"
    >>> utf_text = plaintext.encode('UTF-16LE')
    >>> hashlib.sha1(utf_text).digest().encode('base64')
    'QEy4TXy9dNgleLq+IEcjsQDYm0A=\n'
    

    The above session was done in Python 2; in Python 3 the u prefix can be omitted as all string values are Unicode.