Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 859
Adil Malik Avatar asked Jun 15 '16 20:06

Adil Malik


2 Answers

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

like image 151
Simon Kirsten Avatar answered Nov 17 '22 11:11

Simon Kirsten


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
like image 31
klvntrn Avatar answered Nov 17 '22 11:11

klvntrn