from typing import List from .encoding_base64_base64_decode import base64_decode def base64_url_decode(text: str) -> List[int]: """base64url text back to bytes, with or without correct padding.""" if not isinstance(text, str): raise TypeError("base64url text must be a string") body = [] padding = 0 for ch in text: if ch == "=": padding += 1 continue ok = ("A" <= ch <= "Z") or ("a" <= ch <= "z") or ("0" <= ch <= "9") or ch == "-" or ch == "_" if not ok or padding > 0: raise ValueError( "base64url text may only contain A-Z, a-z, 0-9, - and _, with optional = padding at the end" ) body.append("+" if ch == "-" else "/" if ch == "_" else ch) if len(body) % 4 == 1: raise ValueError( "base64url text cannot be %d characters long; no number of bytes encodes to that" % len(body) ) needed = (4 - len(body) % 4) % 4 if padding != 0 and padding != needed: raise ValueError("base64url text has the wrong amount of = padding") return base64_decode("".join(body) + "=" * needed)