Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert Python Hash method to PHP

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"));

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Can someone help? 🙂

>Solution :

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading