Php's md5 function takes an optional second argument which, if true, returns a smaller hash of length 16 instead of the normal 32 character long hash.
How can we do the same using python's hashlib.md5
.
"an optional second argument which, if true, returns a smaller hash of length 16 instead of the normal 32 character long hash."
This is not true: The second parameter $raw_output
specifies whether the output should be hexadecimal (hex) encoded or in a raw binary string. The hash length does not change but rather the length of the encoded string.
import hashlib
digest = hashlib.md5("asdf").digest() # 16 byte binary
hexdigest = hashlib.md5("asdf").hexdigest() # 32 character hexadecimal
The first should only be used inside your code and not presented to the user as it will contain unprintable characters. That's why you should always use the hexdigest
function if you want to present the hash to a user.
A note for those trying to get the hash in Python 3:
Because Unicode-objects must be encoded before hashing with hashlib
and because strings in Python 3 are Unicode by default (unlike Python 2), you'll need to encode the string using the .encode
method. Using the example above, and assuming utf-8 encoding:
import hashlib
digest = hashlib.md5("asdf".encode("utf-8")).digest() # 16 byte binary
hexdigest = hashlib.md5("asdf".encode("utf-8")).hexdigest() # 32 character hexadecimal
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With