Created
July 12, 2019 17:26
-
-
Save Sparrow1029/c4e830b58995fae7533dc4d6e071d7f9 to your computer and use it in GitHub Desktop.
Implementation of Base64 encoding in Python3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
"""Script to encode & decode strings to and from Base64""" | |
import sys | |
import argparse | |
CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" | |
PAD = "=" | |
LINE_WIDTH = 76 | |
b64_ord = dict(zip(CHARS, range(64))) | |
ord_b64 = dict(zip(range(64), CHARS)) | |
parser = argparse.ArgumentParser(prog='Base64', | |
description='Encode/decode strings to/from Base64.') | |
arg_grp = parser.add_mutually_exclusive_group(required=True) | |
arg_grp.add_argument("-d", action="store", type=str, help="decode <string>", | |
metavar="DECODE") | |
arg_grp.add_argument("-e", action="store", type=str, help="encode <string>", | |
metavar="ENCODE") | |
args = parser.parse_args() | |
# DECODE | |
if args.d: | |
b64_data = args.d | |
out = "" | |
byte_arr = [] | |
for char in b64_data: | |
if char == PAD: | |
break | |
if char == '\n': | |
continue | |
try: | |
byte_arr.append(format(int(b64_ord[char]), '08b')[2:]) | |
except KeyError: | |
print(f'Invalid Base64 character: {char}') | |
sys.exit(2) | |
byte_arr = ''.join(byte_arr) | |
pos = 0 | |
for _ in byte_arr: | |
byte = byte_arr[pos:pos+8] | |
if byte: # Empty string means we are done. | |
out += chr(int(byte, 2)) | |
pos += 8 | |
print(out) | |
#ENCODE | |
if args.e: | |
ascii_data = args.e | |
b64_out = "" | |
byte_arr = [] | |
for char in ascii_data: | |
byte_arr.append(format(ord(char), '08b')) | |
byte_arr = ''.join(byte_arr) | |
pads_needed = len(byte_arr) % 3 | |
pos = 0 | |
line_len = 0 | |
for _ in byte_arr[:0 - pads_needed - 6]: | |
byte = byte_arr[pos:pos+6] | |
if byte: | |
b64_out += ord_b64[(int(byte, 2))] | |
else: | |
break | |
pos += 6 | |
if line_len == LINE_WIDTH: | |
b64_out += '\n' | |
line_len = -1 | |
line_len += 1 | |
b64_out += PAD * pads_needed | |
print(b64_out) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment