7

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.

Mahammad Adil Azeem
  • 9,112
  • 13
  • 57
  • 84

2 Answers2

15

"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.

Dan D.
  • 73,243
  • 15
  • 104
  • 123
Simon Kirsten
  • 2,542
  • 18
  • 21
5

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
klvntrn
  • 71
  • 1
  • 4