Python includes the
hashlib
encryption library, which can also be used for MD5. You can use digest() or hexdigest() methods.Basic example with using hexdigest() method:
Returns the encoded data in hexadecimal format.
import hashlib
str2hash = "Hello world!"
md5hash = hashlib.md5(str2hash.encode('utf-8')).hexdigest()
print (md5hash)
The above example will output:
86fb269d190d2c85f6e0468ceca42a20
Example #2 with with using digest() method:
Returns the encoded data in byte format
import hashlib
str2hash = 'Hello world!'
print(hashlib.md5(str2hash.encode('utf-8')).digest())
Example #2 will output:
b'\x86\xfb&\x9d\x19\r,\x85\xf6\xe0F\x8c\xec\xa4* '
Example #3 with salt before string to be encrypted:
In some cases, it is worth using a salted MD5 hash for added security. This means that you add the string "salt" before or after the string to be encrypted.
import hashlib
salt = 'i#8^*uu' # Your secret key
str2hash = 'Hello world!'
print(hashlib.md5(salt.encode('utf-8') + str2hash.encode('utf-8')).hexdigest())
Example #3 will output:
5e5eb686808a7c39710dccf1ce03a4e6