There are several Python cryptographic modules, but either way, you need to import the appropriate encryption module and then use the module to encrypt the string.
First import the required modules for MD5 encryption:
Copy the Code code as follows:
Import Hashlib
Create a MD5 object
Copy CodeThe code is as follows:
m = Hashlib.md5 ()
Generates an encrypted string, where password is the one to encrypt
Copy CodeThe code is as follows:
M.update (' password ')
Get encrypted string
Copy CodeThe code is as follows:
PSW = M.hexdigest ()
Output
Copy CodeThe code is as follows:
Print PSW
Perform:
Copy CodeThe code is as follows:
5f4dcc3b5aa765d61d8327deb882cf99
For convenience, we can write a function that directly passes the string call to be encrypted
Copy CodeThe code is as follows:
def MD5 (str):
Import Hashlib
m = Hashlib.md5 ()
M.update (str)
Return M.hexdigest ()
Call:
Copy CodeThe code is as follows:
str = MD5 (' password ')
If an incoming parameter is not a string, it will be an error
Copy CodeThe code is as follows:
str = MD5 ([' A ', ' B '])
Error:
Copy CodeThe code is as follows:
Traceback (most recent):
File "D:\python\demo1\c.py", line 9, in
str = MD5 ([' A ', ' B '])
File "D:\python\demo1\c.py", line 5, in MD5
M.update (str)
TypeError: Must is string or buffer, not list
We can detect incoming types and avoid errors
copy code code as follows:
Br>def MD5 (STR):
Import hashlib
Import Types
If Type (str) is types. StringType:
m = hashlib.md5 ()
M.update (str)
return m.hexdigest ()
Else:
Return '
The encrypted string is returned correctly when we pass in the argument as a string, and all other types return null!