Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : error with importing md5

Tags:

python

md5

I have problem with importing md5 library I just use the code below:

import md5
filemd5 = md5.new(password.strip()).hexdigest()

I also have tried this code :

from hashlib import md5
filemd5 = md5.new(password.strip()).hexdigest()

also this code :

from md5 import md5

But none of them are working ! when I run the code,it gives me this error:

11.py", line 1, in <module>
import md5
ImportError: No module named 'md5'

What Should I Do ? Am I Importing The Wrong Library ?

like image 474
Shahrad Avatar asked Sep 10 '16 07:09

Shahrad


1 Answers

md5 is not a module, it is an object. But it has no new method. It just has to be built, like any object.

Use as follows:

import hashlib

m=hashlib.md5(b"text")
print(m.hexdigest())

The b prefix is required by Python 3, and is understood (and ignored by python 2.7). Older versions of python 2 don't accept it (just pass "text" as a string)

results in:

1cb251ec0d568de6a929b520c4aed8d1

You can also create the object empty and update it afterwards (more than once!)

m=hashlib.md5()
m.update(b"text")
m.update(b"other text")
s = "some more text"
m.update(s.encode())

note that Python 3 requires an encoded bytes object, not string, because Python 3 makes a difference between string and binary data. MD5 is useful on binary and strings.

like image 75
Jean-François Fabre Avatar answered Oct 14 '22 15:10

Jean-François Fabre