Base64 encoding and decoding in Python

Source: Internet
Author: User
Tags base64



Introduction:



In some projects, the interface of the message is transmitted through Base64 encryption, so in the automation of the interface, the transmitted parameters need to be Base64 encoded, the received response message decoding;






BASE64 coding is a kind of "anti-gentleman non-villain" encoding method. Widely used in the MIME protocol, as the transmission encoding of e-mail, the resulting encoding is reversible, the latter one or two bits may have "=", the generated encoding is ASCII characters.
Pros: Fast, ASCII characters, not visually understandable
Cons: Coding is long, very easy to crack, only for encryption of non-critical information occasions
BASE64 encoding and decoding in Python2
>>> Import Base64
>>> s = ' I am a string '
>>> A = Base64.b64encode (s)
>>> Print a
ztlkx9fwt/u0rg==
>>> print Base64.b64decode (a)
I'm a string.



Python3 is not the same: because characters in 3.x are Unicode encoded, and the B64encode function has a byte type, you must first transcode it.


import base64

encodestr = base64.b64encode (‘abcr34r344r‘.encode (‘ utf-8 ’))
print (encodestr)
The print result is
b‘YWJjcjM0cjM0NHI = ‘

The result is a little different from what we expected, we just want to get YWJjcjM0cjM0NHI =, and the string is surrounded by b ’’.
At this time someone must have said it, just take it out. . . Don't worry. . .
b means byte, we just need to convert the byte back. . . The source code is as follows
import base64

encodestr = base64.b64encode (‘abcr34r344r‘.encode (‘ utf-8 ’))
print (str (encodestr, 'utf-8'))
The print result is
YWJjcjM0cjM0NHI =

Base64 encoding and decoding in Python


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.