56 lines
1.6 KiB
Python
56 lines
1.6 KiB
Python
class Base64:
|
|
def __init__(self):
|
|
# Base64 alphabet
|
|
self.alphabet = (
|
|
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
|
|
)
|
|
|
|
def encode(self, data: str) -> str:
|
|
# Convert string to bytes and get binary representation
|
|
binary = "".join([format(b, "08b") for b in data.encode()])
|
|
|
|
# Pad with zeros if necessary
|
|
padding = len(binary) % 6
|
|
if padding:
|
|
binary += "0" * (6 - padding)
|
|
|
|
# Split into 6-bit chunks and convert to decimal
|
|
chunks = [binary[i : i + 6] for i in range(0, len(binary), 6)]
|
|
result = "".join(self.alphabet[int(chunk, 2)] for chunk in chunks)
|
|
|
|
# Add padding characters
|
|
padding = len(data) % 3
|
|
if padding:
|
|
result += "=" * (3 - padding)
|
|
|
|
return result
|
|
|
|
def decode(self, data: str) -> str:
|
|
# Remove padding characters
|
|
data = data.rstrip("=")
|
|
|
|
# Convert to binary
|
|
binary = "".join([format(self.alphabet.index(c), "06b") for c in data])
|
|
|
|
# Remove padding zeros
|
|
padding = len(binary) % 8
|
|
if padding:
|
|
binary = binary[:-padding]
|
|
|
|
# Convert binary to bytes and then to string
|
|
bytes_data = [int(binary[i : i + 8], 2) for i in range(0, len(binary), 8)]
|
|
return bytes(bytes_data).decode()
|
|
|
|
|
|
# Example usage
|
|
def example():
|
|
b64 = Base64()
|
|
original = "Hello, World!"
|
|
encoded = b64.encode(original)
|
|
print(f"Original: {original}")
|
|
print(f"Encoded: {encoded}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
example()
|