# -*- coding: utf-8 -*-
# @Author : __LittleQ__
# @FileName: android_base64.py
import base64
DEFAULT = 0 # 默认模式, 每行不超过76个字符
NO_PADDING = 1 # 移除最后的=
NO_WRAP = 2 # 不换行,一行输出
CRLF = 4 # 采用win上的换行符
URL_SAVE = 8 # 采用urlsafe
def decode(content: str, flag: int) -> bytes:
missing_padding = len(content) % 4
if missing_padding != 0:
content = content.ljust(len(content) + (4 - missing_padding), "=")
if flag & URL_SAVE:
result = base64.urlsafe_b64decode(content.encode("utf-8"))
else:
result = base64.b64decode(content.encode("utf-8"))
return result
def encode(content: bytes, flag: int) -> str:
need_wrap = True
need_padding = True
lf = "\n"
if flag & NO_WRAP:
need_wrap = False
if flag & NO_PADDING:
need_padding = False
if flag & CRLF:
lf = "\r\n"
if flag & URL_SAVE:
result = base64.urlsafe_b64encode(content).decode("utf-8")
else:
result = base64.b64encode(content).decode("utf-8")
if not need_padding:
result = result.rstrip("=")
if need_wrap:
n = 76
output = lf.join([result[i:i + n] for i in range(0, len(result), n)])
else:
output = result
return output