The md5 Module
The md5 module is used to calculate message signatures (message digests).
The md5 algorithm calculates a strong 128-bit signature. This means
that if two strings are different, it’s highly likely that their md5
signatures are different as well. To put it another way, given an
md5 digest, it’s supposed to be nearly impossible to come up with a
string that generates that digest. Example 2-35 demonstrates the md5 module.
Example 2-35. Using the md5 Module
File: md5-example-1.py
import md5
hash = md5.new()
hash.update("spam, spam, and eggs")
print repr(hash.digest())
'L\005J\243\266\355\243u`\305r\203\267\020F\303'Note that the checksum is returned as a binary string. Getting a hexadecimal or base64-encoded string is quite easy, though, as Example 2-36 shows.
Example 2-36. Using the md5 Module to Get a Hexadecimal or Base64-Encoded md5 Value
File: md5-example-2.py
import md5
import string
import base64
hash = md5.new()
hash.update("spam, spam, and eggs")
value = hash.digest()
print string.join(map(lambda v: "%02x" % ord(v), value), "")
# in 2.0, the above can be written as
# print hash.hexdigest()
print base64.encodestring(value)
4c054aa3b6eda37560c57283b71046c3
TAVKo7bto3VgxXKDtxBGww==Example 2-37 shows how, among other things, the md5 checksum can be used for
challenge-response authentication (but see the note on random numbers
later).
Example 2-37. Using the md5 Module for Challenge-Response Authentication
File: md5-example-3.py import md5 import string, random def getchallenge(): ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access