pybase64.py
1 import base64 2 import os 3 import string 4 5 charset = string.ascii_uppercase + string.ascii_lowercase + string.digits + "+/" 6 7 8 def base64encode(data: bytes) -> str: 9 bits = "".join([bin(c)[2:].rjust(8, '0') for c in data]) + "0" * ((3 - len(data)) % 3 * 2) 10 chunks = [bits[i * 6:(i + 1) * 6] for i in range(len(bits) // 6)] 11 return "".join([charset[int(c, 2)] for c in chunks]) + "=" * ((3 - len(data)) % 3) 12 13 14 def base64decode(data: str) -> bytes: 15 padding = data.count("=") 16 data = data.strip("=") 17 bits = "".join([bin(charset.index(c))[2:].rjust(6, '0') for c in data]) 18 if padding: 19 bits = bits[:-padding * 2] 20 return bytes([int(bits[i * 8:(i + 1) * 8], 2) for i in range(len(bits) // 8)]) 21 22 23 def test(inp: bytes, enc: callable, enc2: callable, dec: callable): 24 print("Input:", inp) 25 my = enc(inp) 26 print("My Output:", my) 27 correct = enc2(inp).decode() 28 print("Correct Output:", correct) 29 if my == correct: 30 dec = dec(my) 31 print("Decoded:", dec) 32 print(dec == inp) 33 else: 34 print(False) 35 36 37 test(os.urandom(385), base64encode, base64.b64encode, base64decode)