roc-fnb-server/roc_fnb/util/base64.py

30 lines
863 B
Python

from base64 import b64encode
from binascii import a2b_base64
import binascii
def base64_decode(string: str|bytes) -> bytes:
"""
Python's base64.b64_decode requires padding to be correct. This does not.
What silly bullshit.
"""
encoded: bytes = string.encode() if isinstance(string, str) else string
# padc = 4 - len(encoded) % 4
# if padc == 4:
# padc = 0
# fixed = encoded + b'=' * padc
fixed = encoded + b'===='
try:
return a2b_base64(fixed, strict_mode=False)
except binascii.Error as e:
print(f'{string=!r}\n{len(string)=!r}\n{padc=!r}\n{fixed=!r}\n{len(fixed)=!r}')
raise e
def base64_encode(data: bytes) -> str:
"""
Return a base64 encoded string with no padding
Python's b64encode returns bytes. Why?
"""
return b64encode(data).decode('utf-8').rstrip('=')