There are several Python encryption modules, but either way, you need to import the appropriate encryption module before using the module to encrypt the string.
To import the required modules for MD5 encryption first:
Copy Code code as follows:
Creating MD5 objects
Copy Code code as follows:
Generates an encrypted string, where password is the string to be encrypted
Copy Code code as follows:
Get encrypted string
Copy Code code as follows:
Output
Copy Code code as follows:
Perform:
Copy Code code as follows:
5f4dcc3b5aa765d61d8327deb882cf99
For convenience, we can write a function that passes directly to the string call to be encrypted.
Copy Code code as follows:
def MD5 (str):
Import Hashlib
m = Hashlib.md5 ()
M.update (str)
Return M.hexdigest ()
Call:
Copy Code code as follows:
If the passed parameter is not a string, it will error
Copy Code code as follows:
str = MD5 ([' A ', ' B '])
Error:
Copy Code code as follows:
Traceback (most recent call last):
File "D:\python\demo1\c.py", line 9, in <module>
str = MD5 ([' A ', ' B '])
File "D:\python\demo1\c.py", line 5, in MD5
M.update (str)
Typeerror:must be string or buffer, not list
We can detect incoming types and avoid errors
Copy Code code as follows:
def MD5 (str):
Import Hashlib
Import types
If Type (str) is types. StringType:
m = Hashlib.md5 ()
M.update (str)
Return M.hexdigest ()
Else
Return ""
When we pass in the argument for the string can correctly return the encrypted string, the other types are returned empty!
PS: This site also provides an online encryption tool for everyone to refer to the use of:
MD5 Online encryption tool:Http://tools.jb51.net/password/CreateMD5Password