[Python] base64 module

The base64 module is used for base64 encoding and decoding, and is often used for small data transmission. The encoded data is a string, which includes az, AZ, 0-9, /, + a total of 64 characters, which can be represented by 6 bytes, and the written value is 0-63. Therefore, if three bytes are encoded It becomes 4 bytes. If the number of data bytes is not a multiple of 3, 6-bit blocks cannot be accurately divided. At this time, one or two zero-value bytes need to be added after the original data to make the bytes The number is a multiple of 3, and then 1 or 2 '=' are added after the encoded string to indicate a zero-value byte, so in fact it consists of 65 characters in total.

In Python, base64 is a built-in commonly used standard module, we can directly import the base64 module through import and use it directly.

import json,base64
if __name__ == '__main__':
    # 要编码的数据
    data = {
    
    "uname":"Tanch","uid":3}
    # 先转化为bytes类型数据
    data_bytes = json.dumps(data).encode()
    print(type(data_bytes))
    # 编码
    base_data = base64.b64encode(data_bytes)
    print(base_data)
    # 解码
    string_bytes = b"eyJ1bmFtZSI6ICJUYW5jaCIsICJ1aWQiOiAzfQ=="
    ori_data = base64.b64decode(string_bytes).decode()
    # 字符串
    print(ori_data)
    # 变回原来的字典
    data = json.loads(ori_data)
    print(type(data))

The printed results are as follows:

<class 'bytes'>
b'eyJ1bmFtZSI6ICJUYW5jaCIsICJ1aWQiOiAzfQ=='
{
    
    "uname": "Tanch", "uid": 3}
<class 'dict'>

There are only 8 methods actually used by the base64 module, namely encode, decode, encodestring, decodestring, b64encode, b64decode, urlsafe_b64decode, urlsafe_b64encode.

The 8 of them can be divided into 4 groups in pairs, encode and decode, which are specially used to encode and decode files, and can also encode and decode data in StringIO; encodestring and decodestring are specially used to encode and decode strings ; A set of b64encode and b64decode is used to encode and decode strings, and has a function of replacing symbol characters; a set of urlsafe_b64encode and urlsafe_b64decode is used to encode and decode urls specifically to base64.

The code example is as follows:

b64encode and b64decode: operations on strings

import base64

st = 'hello world!'.encode()#默认以utf8编码
res = base64.b64encode(st)
print(res.decode())#默认以utf8解码
res = base64.b64decode(res)
print(res.decode())#默认以utf8解码

The output is:

aGVsbG8gd29ybGQh
hello world!

The processing object of encoding and decoding is byte, so the original data must be encoded first, so that the original str type becomes byte, and the byte object is directly output after decoding, so it needs to be decoded into a str object.

Guess you like

Origin blog.csdn.net/wzk4869/article/details/132636807