Hashlib and Base64 cryptographic modules in Python use an instance _python

Source: Internet
Author: User
Tags base64 md5 md5 encryption in python

See several bloggers through the module of the break-by-learn python, I also imitate, this article about Python encryption involved in the module.

Hashlib

Hashlib module Support encryption algorithm has MD5 SHA1 sha224 sha256 sha384 sha512 (Encryption principle please refer to here), it is very simple to use.

Take MD5 encryption For example, there are two ways:

One, append mode

code example:

Copy Code code as follows:

Import Hashlib #引入hashlib模块

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

Two or one words

If you do not need to append, just encrypt a paragraph of text, which can be used in this form, code example:

Copy Code code as follows:

Import Hashlib

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

In addition, algorithms such as MD5 also provide properties such as Digest_size and Block_size, indicating the size of the text after encryption.

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

Base64

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

Copy Code code 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 to provide more encryption, and later when learning.

Related Article

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.