Python uses MD5 to encrypt string samples _python

Source: Internet
Author: User
Tags md5 md5 encryption

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:

Import Hashlib

Creating MD5 objects
Copy Code code as follows:

m = Hashlib.md5 ()

Generates an encrypted string, where password is the string to be encrypted
Copy Code code as follows:

M.update (' password ')

Get encrypted string
Copy Code code as follows:

PSW = M.hexdigest ()

Output
Copy Code code as follows:

Print PSW

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:

str = MD5 (' password ')

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

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.