Python uses MD5 encryption string example

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