Examples of hashlib and base64 encryption modules in python

Source: Internet
Author: User
This article describes how to use the hashlib and base64 encryption modules in python. The hashlib module supports the md5sha1sha224sha256sha384sha512 encryption algorithms, if you need python, You can see several bloggers learn python by breaking through the modules. I also follow the same example. This article describes the modules involved in python encryption.

Hashlib

The hashlib module supports the md5 sha1 sha1_sha256 sha384 sha512 encryption algorithm (for details about the encryption principle, refer to here), which is easy to use.

Md5 encryption is used as an example. There are two methods:

I. append Mode

Sample Code:

The Code is as follows:


Import hashlib # introduce the hashlib Module

Mm = hashlib. md5 () # create an md5 object
Mm. update ("Hello") # encrypt text using the update Method
Mm. update ("world! ") # Append. The two sentences are equivalent to mm. update (" Hello world! ")
Print mm. digest () # output encrypted binary data
Print mm. hexdigest () # output the encrypted hexadecimal data

2. One sentence

If you do not need to append an object, you only need to encrypt a piece of text in this form. The sample code is as follows:

The Code is as follows:


Import hashlib

Hashlib. new ("md5", "Hello world! "). Digest ()


In addition, md5 and other algorithm objects provide digest_size and block_size attributes to indicate the size of the encrypted text.

For other encryption algorithms, you only need to replace "md5" in the code.

Base64

The encryption algorithm provided by this module is not secure, but is very simple and sometimes used.
Sample Code:

The Code is as follows:


Import base64

A = "Hello world! "
B = base64.encodestring (a) # Encryption
C = base64.decodestring (B) # decrypt

Print a = c


Python also has many third-party modules to provide more encryption methods.

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.