编程技术分享平台

网站首页 > 技术教程 正文

Python 中 base64 编码与解码

xnh888 2025-01-12 19:39:37 技术教程 19 ℃ 0 评论

base64 是经常使用的一种加密方式,在 Python 中有专门的库支持。

本文主要介绍在 Python2 和 Python3 中的使用区别:

在 Python2 环境:

Python 2.7.16 (default, Mar 25 2021, 03:11:28)
[GCC 4.2.1 Compatible Apple LLVM 11.0.3 (clang-1103.0.29.20) (-macos10.15-objc- on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import base64
>>> s = 'AlwaysBeta'
>>> a = base64.b64encode(s)
>>> print a
QWx3YXlzQmV0YQ==
>>>
>>> base64.b64decode(a)
'AlwaysBeta'

在 Python3 环境:

Python3 中有一些区别,因为 Python3 中字符都是 unicode 编码,而 b64encode函数的参数为 byte 类型,所以必须先转码。

Python 3.8.5 (default, Jul 21 2020, 10:42:08)
[Clang 11.0.0 (clang-1100.0.33.17)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import base64
>>> a = base64.b64encode('AlwaysBeta'.encode('utf-8'))
>>> a
b'QWx3YXlzQmV0YQ=='
>>> str(a, 'utf-8')
'QWx3YXlzQmV0YQ=='
>>>
>>> base64.b64decode(a)
b'AlwaysBeta'
>>> str(base64.b64decode(a), 'utf-8')
'AlwaysBeta'

以上就是本文的全部内容,如果觉得有用的话欢迎点赞转发,多谢。


Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表