Home > Enterprise >  Convert Python Hash method to PHP
Convert Python Hash method to PHP

Time:04-11

I'm currently trying to convert a Python hash method to PHP.

Python: password = base64.b64encode(hashlib.sha1(user_password.encode('ascii')).digest()).decode("utf-8")

PHP: password = base64_encode(openssl_digest(sha1(ord($user_password)), "sha256"));

Can someone help? :)

CodePudding user response:

The equivalent PHP code is:

base64_encode(sha1($user_password, true))

In detail:

  • user_password.encode('ascii') has no equivalent, as PHP only has byte arrays as string type which cannot be encoded or decoded to/from another string type.
  • hashlib.sha1(...).digest() is equivalent to sha1(..., true). Just sha1(...) is equivalent to hashlib.sha1(...).hexdigest(). digest has nothing to do with openssl_digest; it just gives you the current hash digest value. Contrary to PHP, you can successively update a hash in Python and thus need an explicit "end" somewhere. In PHP you can only feed one value in and get one value out.
  • base64.b64encode(...).decode("utf-8") is simply base64_encode to encode the raw bytes returned by the SHA1 hash to base 64. Again, there's no equivalent to decode.
  • Related