Python Module Introduction-Base16, BASE32, Base64 data encoding

Source: Internet
Author: User
Tags base64 chr http post printable characters rfc

Brief introduction

Features: RFC 3548:base16, BASE32, Base64 data encoding. Converts the binary data to an ASCII sequence that is suitable for plaintext protocol transmission. Transformation
8bits contains valid data for 6, 5, or 4bits for each byte, such as SMTP, part of the URL, or part of the HTTP POST. Reference:
RFC 3548. The encoding algorithm differs from Uuencode.
Type: Standard library
Related modules: UU, BinHex, UU, Quopri


Base64 is a representation of binary data based on 64 printable characters. Since 2 of 6 times equals 64, every 6
The single element is a unit that corresponds to a printable character. Three bytes have 24 bits, corresponding to 4 Base64 units, or 3 bytes
It needs to be represented by 4 printable characters. It can be used as the transmission encoding for e-mail. printable characters in Base64 include the letter A-
Z, A-Z, number 0-9, so there are 62 characters, and two printable symbols are different in different systems. Then in the front of the 6-bit
Two 0, forming a 8-bit form of a byte. Some other encoding methods, such as Uuencode, and later BinHex versions use different
The 64 character set represents 6 binary digits, but they are not called Base64.


Base64 is often used to represent, transmit, and store some binary data in situations where text data is normally processed. That includes MIME
Email,email via MIME, which stores complex data in XML.

The Python Base64 module provides data encoding and decoding in the RFC3548 (converting binary data to fit the plaintext protocol
The ASCII sequence, as specified in RFC3548. The standard defines the BASE16,BASE32 and Base64 algorithms, encoding and decoding any binary string into a text string so that it can be sent securely via e-mail, as part of the URL, or included in an HTTP POST request.


The Base64 module provides two interfaces. Modern interfaces support the use of three-letter encoded and decoded string objects. The traditional interface provides
Code and Decode file objects and strings, but only the standard Base64 letters are used. Traditional interfaces do not introduce here.


Base64, Base32, BASE16 can be encoded to convert 8 bytes to 6-bit, 5-bit, and 4-bit respectively. 16,32,64 the number of words to use respectively
Character encoding.


For more information on Base64, see
Http://zh.wikipedia.org/wiki/Base64,http://tools.ietf.org/html/rfc822,http://tools.ietf.org/html/rfc14
21,http://tools.ietf.org/html/rfc2045.

Quick Start

See the examples in the Python module introduction:

>>> Import base64>>> encoded = Base64.b64encode (' Data to be encoded ') >>> encoded ' ZGF0YSB0BYBIZSBLBMNVZGVK ' >>> data = base64.b64decode (encoded) >>> data ' data to be encoded '

Base64.b64encode (s[, Altchars]): Encodes a string using BASE64. S is the string to encode. Altchars are strings used to replace + and/, which have special meanings in URLs and file systems, and often need to be replaced.
Base64.b64decode (s[, Altchars]): Decodes the BASE64 encoded string. S is the string to decode. Altchars and B64encode are the same.
? Base64.standard_b64encode (s): refer to B64encode.
? Base64.standard_b64decode (s): refer to B64decode.

BASE64 encoding and decoding


BASE64 encoding and decoding

#!/usr/bin/env python# encoding:utf-8## Copyright (c) Doug Hellmann All rights reserved.# "" "" "" __version__ = "$Id $" # End_pymotw_headerimport Base64import textwrap# Load This source file and strip the Header.with open (__file__, ' RT ') as InP Ut:raw = Input.read () Initial_data = Raw.split (' #end_pymotw_header ') [1]encoded_data = Base64.b64encode (initial_data) num_initial = Len (initial_data) # There'll never be + than 2 padding bytes.padding = 3-(num_initial% 3) print '%d by TES before encoding '% Num_initialprint ' Expect%d padding bytes '% paddingprint '%d bytes after encoding '% Len (encoded_d ATA) Printprint Encoded_data

? Execution results

$ python base64_b64encode.py168 bytes before encodingexpect 3 padding bytes224 bytes after encodingcgppbxbvcnqgymfzzty0cm Ltcg9ydcb0zxh0d3jhcaokiybmb2fkihroaxmgc291cmnligzpbgugyw5kihn0cmlwihrozsbozwfkzxiucndpdgggb3blbihfx2zpbgvfxywgj3j0jykgyxm Gaw5wdxq6ciagicbyyxcgpsbpbnb1dc5yzwfkkckkicagigluaxrpywxfzgf0ysa9ihjhdy5zcgxpdcgn

BASE64 encoded 4 bytes corresponds to the actual 3 bytes, less than four bytes, the latter part is usually filled with an equal sign. In extreme cases,
A byte needs to be represented by 4 Base64 encodings.

>>> Import base64>>> encoded = Base64.b64encode (' a ') >>> encoded ' yq== '

Base64 decoding See Introduction to the QuickStart section.


Url-safe

? Base64.urlsafe_b64encode (s):
? Base64.urlsafe_b64decode (s):
Base64 uses + and/, but these 2 characters also have a special meaning in the URL. Using Urlsafe can solve this problem. + Replaced by-,
/Replace with _.

Import base64encodes_with_pluses = chr (251) + CHR (239) encodes_with_slashes = chr (255) * 2for original in [ENCODES_WITH_PL Uses, encodes_with_slashes]:p rint ' Original: ', repr (Original) print ' Standard encoding: ', Base64.standard_b64encode ( Original) print ' Url-safe encoding: ', Base64.urlsafe_b64encode (original) print

? Execution results

$ python base64_urlsafe.pyoriginal: ' \xfb\xef ' standard encoding: ++8=URL-SAFE encoding:--8=original: ' \xff\xff ' Standard encoding://8=URL-SAFE encoding: __8=

Other codes

The BASE32 contains 26 uppercase letters and 2-7 digits.
? Base64.b32encode (s): Encodes a string using BASE32. S is the string to encode.
? Base64.b32decode (s[, casefold[, MAP01]): Decodes the BASE32 encoded string. S is the string to decode.
Casefold Indicates whether lowercase letters are allowed. MAP01 indicates that 0 is allowed to indicate that 0,1 represents L.

Import base64original_string = ' This was the data, in the clear. ' print ' Original: ', original_stringencoded_string = Base64.b32encode (original_string) print ' encoded: ', encoded_ stringdecoded_string = Base64.b32decode (encoded_string) print ' decoded: ', decoded_string


? Execution results

$ Python base64_base32.pyOriginal:This is the data, in the clear. Encoded:krugs4zanfzsa5dimuqgiylumewca2loeb2gqzjamnwgkylsfy======decoded:this is the data and in the clear.

The BASE16 contains 16 16-in uppercase digits. Similar to Base64.b16encode (s), Base64.b16decode (s[,
Casefold]).

Import base64original_string = ' This was the data, in the clear. ' print ' Original: ', original_stringencoded_string = Base64.b16encode (original_string) print ' encoded: ', encoded_ stringdecoded_string = Base64.b16decode (encoded_string) print ' decoded: ', decoded_string

?
Execution results

$ Python base64_base16.pyOriginal:This is the data, in the clear. Encoded:546869732069732074686520646174612c20696e2074686520636c6561722edecoded:this is the data and in the clear. Ascii85 and Base85 support are added to the Python3.4. This is not a detailed introduction here. The function is as follows:? Base64.a85encode (S, *, Foldspaces=false, wrapcol=0, Pad=false, Adobe=false)? Base64.a85decode (S, *, Foldspaces=false, Adobe=false, ignorechars=b ' TNRV ')? Base64.b85encode (S, pad=false)? Base64.b85decode (b)


    • Author Blog: http://my.oschina.net/u/1433482

    • Genre: Translation plus finishing

    • Download the latest PDF version of this article. This article was originally created based on the LibreOffice's ODT format, and the copied format has some changes, and it is recommended to view the original PDF.

    • Python2 Official website: http://docs.python.org/2/library/base64.html

    • Python3 Official website: https://docs.python.org/3/library/base64.html

    • Python Standard library Pymotw:http://pymotw.com/2/base64/index.html#module-base64


Python Module Introduction-Base16, BASE32, Base64 data encoding

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.