草庐IT

python标准模块介绍 -Base64: Base64, Base85等数据编码

python测试开发 2023-10-21 原文

简介

功能:RFC 3548: Base16, Base32, Base64 数据编码。转换二进制数据为适合明文协议传输的 ASCII 序列。转换

8bits 为每个字节包含 6,5 或 4bits 的有效数据,比如 SMTP, URL 的一部分或者 HTTP POST 的一部分。参考: RFC 3548。编码算法不同于 uuencode。

类型:标准库

相关模块:uu, binhex, uu, quopri

Base64 是一种基于 64 个可打印字符来表示二进制数据的表示方法。由于 2 的 6 次方等于 64,所以每 6 个位元为一个单元,对应某个可打印字符。三个字节有 24 个位元,对应于 4 个 Base64 单元,即 3 个字节 需要用 4 个可打印字符来表示。它可用来作为电子邮件的传输编码。在 Base64 中的可打印字符包括字母 A- Z、a-z、数字 0-9,这样共有 62 个字符,此外两个可打印符号在不同的系统中而不同。之后在 6 位的前面补 两个 0,形成 8 位一个字节的形式。一些如 uuencode 的其他编码方法,和之后 binhex 的版本使用不同的 64 字符集来代表 6 个二进制数字,但是它们不叫 Base64。

Base64 常用于在通常处理文本数据的场合,表示、传输、存储一些二进制数据。包括 MIME 的email,email via MIME,在 XML 中存储复杂数据。

Python Base64 模块提供了 RFC3548 中的数据编码和解码(转换二进制数据为适合明文协议传输的ASCII 序列,如 RFC3548 中指定。该标准定义了 Base16,Base32 和 Base64 算法,编码和解码的任意二进制字符串转换为文本字符串,这样就可以通过电子邮件安全发送,作为网址的一部分,或包含在 HTTP POST 请求中。

Base64 模块提供两个接口。新式接口支持使用三个字母的编码和解码的字符串对象。传统接口提供了编码和解码文件对象和字符串,但只使用了标准的 Base64 字母。传统接口这里不做介绍。

base64、 base32、 base16 可以分别编码转化 8 位字节为 6 位、 5 位、 4 位。 16,32,64 分别表示用多少个字

符来编码。

更多 base64 的资料,参见

http://zh.wikipedia.org/wiki/Base64,http://tools.ietf.org/html/rfc822

http://tools.ietf.org/html/rfc1421

http://tools.ietf.org/html/rfc2045

快速入门

请看 python 模块介绍中的实例:


>>> import base64

>>> encoded = base64.b64encode('data to be encoded')

>>> encoded

'ZGF0YSB0byBiZSBlbmNvZGVk'

>>> data = base64.b64decode(encoded)

>>> data

'data to be encoded'

base64.b64encode(s[, altchars]):使用 Base64 编码字符串。s 是要编码的字符串。altchars 是用来替换+和/的字符串,它们在 url 和文件系统中它们有特殊含义,通常需要替换。

base64.b64decode(s[, altchars]): 解码 Base64 编码的字符串。s 为要解码的字符串。altchars 和b64encode 相同。

• base64.standard_b64encode ( s ) : 参考 b64encode。

• base64.standard_b64decode ( s ) :参考 b64decode。

Base64 编码解码

Base64 编码解码


#!/usr/bin/env python

# encoding: utf-8

#

# Copyright (c) 2008 Doug Hellmann All rights reserved.

#

"""

"""

__version__ = "$Id$"

#end_pymotw_header

import base64

import textwrap

# Load this source file and strip the header.

with open(__file__, 'rt') as input:

raw = input.read()

initial_data = raw.split('#end_pymotw_header')[1]

encoded_data = base64.b64encode(initial_data)

num_initial = len(initial_data)

# There will never be more than 2 padding bytes.

padding = 3 - (num_initial % 3)

print '%d bytes before encoding' % num_initial

print 'Expect %d padding bytes' % padding

print '%d bytes after encoding' % len(encoded_data)

print

print encoded_data

➢执行结果


$ python base64_b64encode.py

168 bytes before encoding

Expect 3 padding bytes

224 bytes after encoding

CgppbXBvcnQgYmFzZTY0CmltcG9ydCB0ZXh0d3JhcAoKIyBMb2FkIHRoaXMgc291cmNlIGZpbGUgYW5kIHN0cmlwIHRoZSBoZWFk

ZXIuCndpdGggb3BlbihfX2ZpbGVfXywgJ3J0JykgYXMgaW5wdXQ6CiAgICByYXcgPSBpbnB1dC5yZWFkKCkKICAgIGluaXRpYWxfZGF0

YSA9IHJhdy5zcGxpdCgn

Base64 编码的 4 个字节对应实际的 3 个字节,不足四个字节时,后面部分通常用等号填充。极端的情况下, 一个字节需要用 4 个 Base64 编码来表示。


>>> import base64

>>> encoded = base64.b64encode('a')

>>> encoded

'YQ=='

Base64 解码参见快速入门部分介绍。

URL-Safe

•base64.urlsafe_b64encode(s):

•base64.urlsafe_b64decode(s):

Base64 默认会使用+和/, 但是这 2 个字符在 url 中也有特殊含义。使用 urlsafe 可以解决这个问题。 +替换为-, /替换为_。


import base64

encodes_with_pluses = chr(251) + chr(239)

encodes_with_slashes = chr(255) * 2

for original in [ encodes_with_pluses, encodes_with_slashes ]:

print 'Original

:', repr(original)

print 'Standard encoding:', base64.standard_b64encode(original)

print 'URL-safe encoding:', base64.urlsafe_b64encode(original)

print

➢执行结果


$ python base64_urlsafe.py

Original

: '\xfb\xef'

Standard encoding: ++8=

URL-safe encoding: --8=

Original

: '\xff\xff'

Standard encoding: //8=

URL-safe encoding: __8=

其他编码

Base32 包含 26 个大写字母和 2-7 的数字。

• base64.b32encode(s):使用 Base32 编码字符串。s 是要编码的字符串。

• base64.b32decode(s[, casefold[, map01]]):解码 Base32 编码的字符串。s 为要解码的字符串 。

casefold 表示是否允许小写字母。 map01 表示允许 0 表示 0,1 表示 L 。


import base64

original_string = 'This is the data, in the clear.'

print 'Original:', original_string

encoded_string = base64.b32encode(original_string)

print 'Encoded :', encoded_string

decoded_string = base64.b32decode(encoded_string)

print 'Decoded :', decoded_string

➢执行结果


$ python base64_base32.py

Original: This is the data, in the clear.

Encoded : KRUGS4ZANFZSA5DIMUQGIYLUMEWCA2LOEB2GQZJAMNWGKYLSFY======

Decoded : This is the data, in the clear.

Base16 包含 16 个 16 进制大写数字。类似的有 base64.b16encode(s) ,base64.b16decode(s[,

casefold]) 。


import base64

original_string = 'This is the data, in the clear.'

print 'Original:', original_string

encoded_string = base64.b16encode(original_string)

print 'Encoded :', encoded_string

decoded_string = base64.b16decode(encoded_string)

print 'Decoded :', decoded_string

执行结果


$ python base64_base16.py

Original: This is the data, in the clear.

Encoded : 546869732069732074686520646174612C20696E2074686520636C6561722E

Decoded : This is the data, in the clear.

Python3.4 中增加了 Ascii85 和 base85 支持 。这里暂不做详细介绍。函数如下:

• 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)

参考资料

有关python标准模块介绍 -Base64: Base64, Base85等数据编码的更多相关文章

  1. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  2. ruby - 在 64 位 Snow Leopard 上使用 rvm、postgres 9.0、ruby 1.9.2-p136 安装 pg gem 时出现问题 - 2

    我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po

  3. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  4. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  5. ruby - Ruby 有 `Pair` 数据类型吗? - 2

    有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳

  6. C# 到 Ruby sha1 base64 编码 - 2

    我正在尝试在Ruby中复制Convert.ToBase64String()行为。这是我的C#代码:varsha1=newSHA1CryptoServiceProvider();varpasswordBytes=Encoding.UTF8.GetBytes("password");varpasswordHash=sha1.ComputeHash(passwordBytes);returnConvert.ToBase64String(passwordHash);//returns"W6ph5Mm5Pz8GgiULbPgzG37mj9g="当我在Ruby中尝试同样的事情时,我得到了相同sha

  7. Python 相当于 Perl/Ruby ||= - 2

    这个问题在这里已经有了答案:关闭10年前。PossibleDuplicate:Pythonconditionalassignmentoperator对于这样一个简单的问题表示歉意,但是谷歌搜索||=并不是很有帮助;)Python中是否有与Ruby和Perl中的||=语句等效的语句?例如:foo="hey"foo||="what"#assignfooifit'sundefined#fooisstill"hey"bar||="yeah"#baris"yeah"另外,类似这样的东西的通用术语是什么?条件分配是我的第一个猜测,但Wikipediapage跟我想的不太一样。

  8. ruby - 将 spawn() 的标准输出/标准错误重定向到 Ruby 中的字符串 - 2

    我想使用spawn(针对多个并发子进程)在Ruby中执行一个外部进程,并将标准输出或标准错误收集到一个字符串中,其方式类似于使用Python的子进程Popen.communicate()可以完成的操作。我尝试将:out/:err重定向到一个新的StringIO对象,但这会生成一个ArgumentError,并且临时重新定义$stdxxx会混淆子进程的输出。 最佳答案 如果你不喜欢popen,这是我的方法:r,w=IO.pipepid=Process.spawn(command,:out=>w,:err=>[:child,:out])

  9. java - 什么相当于 ruby​​ 的 rack 或 python 的 Java wsgi? - 2

    什么是ruby​​的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht

  10. ruby - 我如何添加二进制数据来遏制 POST - 2

    我正在尝试使用Curbgem执行以下POST以解析云curl-XPOST\-H"X-Parse-Application-Id:PARSE_APP_ID"\-H"X-Parse-REST-API-Key:PARSE_API_KEY"\-H"Content-Type:image/jpeg"\--data-binary'@myPicture.jpg'\https://api.parse.com/1/files/pic.jpg用这个:curl=Curl::Easy.new("https://api.parse.com/1/files/lion.jpg")curl.multipart_form_

随机推荐