This article mainly introduces the example of using MD5 to encrypt strings in Python. This article also reminds you of some possible errors. you can refer to several Python encryption modules, however, no matter which encryption method is used, you must first import the corresponding encryption module and then use the module to encrypt the string.
Import the required md5 encryption module first:
The code is as follows:
Import hashlib
Create an md5 object
The code is as follows:
M = hashlib. md5 ()
Generate an encrypted string. the password is the string to be encrypted.
The code is as follows:
M. update ('password ')
Get encrypted string
The code is as follows:
Psw = m. hexdigest ()
Output
The code is as follows:
Print psw
Run:
The code is as follows:
5f4dcc3b5aa765d61d8327deb882cf99
For convenience, we can write a function and directly input the string to be encrypted for calling.
The code is as follows:
Def md5 (str ):
Import hashlib
M = hashlib. md5 ()
M. update (str)
Return m. hexdigest ()
Call:
The code is as follows:
Str = md5 ('password ')
If the input parameter is not a string, an error is returned.
The code is as follows:
Str = md5 (['A', 'B'])
Error:
The code is as follows:
Traceback (most recent call last ):
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 be string or buffer, not list
We can detect incoming types to avoid errors.
The code is 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''
If the input parameter is a string, the encrypted string is returned correctly. if the input parameter is of another type, null is returned!