'convert String to MD5

Ok I am trying to write a basic converter of a string to md5 hash code but when I run my program I keep getting an error that say's:

Traceback (most recent call last):
  File "C:\Users\Shane\Documents\Amer CISC\lab4.py", line 30, in <module>
    assertEqual (computeMD5hash("The quick brown fox jumps over the lazy dog"),("9e107d9d372bb6826bd81d3542a419d6"))
  File "C:\Users\Shane\Documents\Amer CISC\lab4.py", line 27, in computeMD5hash
    m.update(string)
TypeError: Unicode-objects must be encoded before hashing

My code looks like this:

def computeMD5hash(string):
    import hashlib
    from hashlib import md5
    m = hashlib.md5()
    m.update((string))
    md5string=m.digest()
    return md5string


Solution 1:[1]

Rather than trying to hash the string, you should hash an encoded byte sequence. Instead of

>>> import hashlib
>>> hashlib.md5("fred")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Unicode-objects must be encoded before hashing

you should encode it, e.g.:

>>> "fred".encode("utf")
b'fred'
>>> hashlib.md5("fred".encode("utf")).hexdigest()
'570a90bfbf8c7eab5dc5d4e26832d5b1'

In Python 2 you could get away without doing this, and it led to no end of unnoticed bugs. Fortunately Python 3 has much saner unicode support, and distinguishes between bytes and strings.

Solution 2:[2]

Seems you have to encode the string before hashing:

http://www.dreamincode.net/forums/topic/246026-generating-string-hash-issue/

Solution 3:[3]

All of the above answers work fine. You can also try this, with a function

import hashlib

def md5hasher(what_text):       
    return hashlib.md5(what_text.encode("utf")).hexdigest()

try it!

md5hasher(your_text_to_encrypt)

Your output would be with 123456 as your_text_to_encrypt

"e10adc3949ba59abbe56e057f20f883e"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DSM
Solution 2 gabga
Solution 3 M E S A B O