Examples of Hashlib and Base64 cryptographic modules used in Python

Source: Internet
Author: User
See a few bloggers through the module of the Conquer learning Python, I also imitate, this article about the Python encryption involved in the module.

Hashlib

The cryptographic algorithms supported by the Hashlib module are MD5 SHA1 sha224 sha256 sha384 sha512 (for the encryption principle, refer to here), which is easy to use.

Take MD5 encryption as an example, there are two methods:

One, append mode

code example:

The code is as follows:


Import Hashlib #引入hashlib模块

mm = HASHLIB.MD5 () #创建一个md5对象
Mm.update ("Hello") #通过update方法加密文本
Mm.update ("world!") #追加, these two sentences are equivalent to Mm.update ("Hello world!")
Print mm.digest () #输出加密后的二进制数据
Print mm.hexdigest () #输出加密后的十六进制数据

Two or one words

If you don't need to append, just encrypt a piece of text, you can use this form, code example:

The code is as follows:


Import Hashlib

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


In addition, algorithmic objects such as MD5 provide properties such as Digest_size and block_size, which indicate the size of the text after encryption.

For other cryptographic algorithms, just replace the "md5" in the code, no longer an example.

Base64

The cryptographic algorithms provided by this module are not secure, but they are very simple and sometimes useful.
code example:

The code is as follows:


Import Base64

A = "Hello world!"
b = base64.encodestring (a) #加密
c = base64.decodestring (b) #解密

Print A==c


Python also has a number of third-party modules that provide more encryption, which you will learn later.
  • 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.