python base64

描述:

适用python3

代码:

# -*- coding: utf8 -*-
import base64


def b64_encode(content_str):
    content_bytes = content_str.encode('utf-8')
    content_bytes = base64.b64encode(content_bytes)
    content_str = content_bytes.decode('utf-8')
    return content_str


def b64_decode(content_str):
    if len(content_str) % 4 !=0:
        content_str += '=' * (4 - len(content_str) % 4)
    content_bytes = content_str.encode('utf-8')
    content_bytes = base64.b64decode(content_bytes)
    content_str = content_bytes.decode('utf-8')
    return content_str


if __name__ == '__main__':
    s = 'hello world!'
    print(s)
    s = b64_encode(s)
    print(s)
    s = b64_decode(s)
    print(s)

输出:

hello world!
aGVsbG8gd29ybGQh
hello world!

你可能感兴趣的:(开发,杂碎)