base64.py 622 B

123456789101112131415161718192021222324
  1. from base64 import b64encode, b64decode
  2. import binascii
  3. __all__ = ["base64", "unbase64"]
  4. Base64String = str
  5. def base64(s: str) -> Base64String:
  6. """Encode the string s using Base64."""
  7. b: bytes = s.encode("utf-8") if isinstance(s, str) else s
  8. return b64encode(b).decode("ascii")
  9. def unbase64(s: Base64String) -> str:
  10. """Decode the string s using Base64."""
  11. try:
  12. b: bytes = s.encode("ascii") if isinstance(s, str) else s
  13. except UnicodeEncodeError:
  14. return ""
  15. try:
  16. return b64decode(b).decode("utf-8")
  17. except (binascii.Error, UnicodeDecodeError):
  18. return ""