Example of using MD5 to encrypt a string in Python

Source: Internet
Author: User
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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.