How can I generate this MD5 sum using Python md5?

How can I get the MD5 sum of a string in Python?

I’m working with the Flickr API and need to generate the api_sig value by calculating the MD5 sum of a string. How can I do this in Python?

For example, given the string:

000005fab4534d05api_key9a0554259914a86fb9e7eb014e4e5d52permswrite

The MD5 sum should be:

a02506b31c1cd46c2e0b6380fb94eb3d

How can I generate this MD5 sum using Python md5?

The hashlib module in Python provides an easy way to generate MD5 hashes.

import hashlib

def get_md5_sum(input_string):
    return hashlib.md5(input_string.encode()).hexdigest()

input_string = "000005fab4534d05api_key9a0554259914a86fb9e7eb014e4e5d52permswrite"
md5_sum = get_md5_sum(input_string)
print(md5_sum)

If you are concerned about encoding issues, ensure to use the UTF-8 encoding explicitly.

import hashlib

def get_md5_sum(input_string):
    return hashlib.md5(input_string.encode('utf-8')).hexdigest()

input_string = "000005fab4534d05api_key9a0554259914a86fb9e7eb014e4e5d52permswrite"
print(get_md5_sum(input_string))

Instead of directly passing the string, you can also use the update() method in the hashlib module.

import hashlib

def get_md5_sum(input_string):
    m = hashlib.md5()
    m.update(input_string.encode())
    return m.hexdigest()

input_string = "000005fab4534d05api_key9a0554259914a86fb9e7eb014e4e5d52permswrite"
print(get_md5_sum(input_string))

The solutions will return the MD5 sum:

a02506b31c1cd46c2e0b6380fb94eb3d

Each of the methods uses Python md5 to generate the hash value, and you can choose the one that fits your needs.