Python: How to create a 16 character long digest using hashlib.md5 algorithm?

Adil Malik picture Adil Malik · Jun 15, 2016 · Viewed 7.1k times · Source

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.

Answer

Simon Kirsten picture Simon Kirsten · Jun 15, 2016

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