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 −

  1. base64.decode(input, output) − It decodes the input value parameter specified and stores the decoded output as an object.

  2. 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)

Output

base64 编码的代码给你以下输出:-

The code for base64 encoding gives you the following output −

base64

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)

Output

base64 解码的代码给你以下输出:-

The code for base64 decoding gives you the following output −

base64 decoding

Difference between ASCII and base64

在对数据进行编码时,使用 ASCII 和 base64 时,你可以观察到以下区别:-

You can observe the following differences when you work on ASCII and base64 for encoding data −

  1. When you encode text in ASCII, you start with a text string and convert it to a sequence of bytes.

  2. When you encode data in Base64, you start with a sequence of bytes and convert it to a text string.

Drawback

Base64 算法通常用于在数据库中存储密码。主要缺点是每个解码后的单词都可以通过任何在线工具轻松编码,入侵者可以轻松获取信息。

Base64 algorithm is usually used to store passwords in database. The major drawback is that each decoded word can be encoded easily through any online tool and intruders can easily get the information.