Cryptography With Python 简明教程
Base64 Encoding and Decoding
Base64 编码将二进制数据转换为文本格式,该格式通过用户可以安全处理文本的通信通道传输。Base64 也称为 Privacy enhanced Electronic mail (PEM) ,主要用于电子邮件加密过程。
Base64 encoding converts the binary data into text format, which is passed through communication channel where a user can handle text safely. Base64 is also called as Privacy enhanced Electronic mail (PEM) and is primarily used in email encryption process.
Python 包含一个名为 BASE64 的模块,其中包括两个主要函数,如下所示:-
Python includes a module called BASE64 which includes two primary functions as given below −
-
base64.decode(input, output) − It decodes the input value parameter specified and stores the decoded output as an object.
-
Base64.encode(input, output) − It encodes the input value parameter specified and stores the decoded output as an object.
Program for Encoding
可以使用以下代码段执行 base64 编码:-
You can use the following piece of code to perform base64 encoding −
import base64
encoded_data = base64.b64encode("Encode this text")
print("Encoded text with base 64 is")
print(encoded_data)
Program for Decoding
可以使用以下代码段执行 base64 解码:-
You can use the following piece of code to perform base64 decoding −
import base64
decoded_data = base64.b64decode("RW5jb2RlIHRoaXMgdGV4dA==")
print("decoded text is ")
print(decoded_data)
Difference between ASCII and base64
在对数据进行编码时,使用 ASCII 和 base64 时,你可以观察到以下区别:-
You can observe the following differences when you work on ASCII and base64 for encoding data −
-
When you encode text in ASCII, you start with a text string and convert it to a sequence of bytes.
-
When you encode data in Base64, you start with a sequence of bytes and convert it to a text string.