Skip to content

Instantly share code, notes, and snippets.

@asdofindia
Created June 12, 2021 20:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asdofindia/9b7d4cd1d1d7e3f85c250605c583ca52 to your computer and use it in GitHub Desktop.
Save asdofindia/9b7d4cd1d1d7e3f85c250605c583ca52 to your computer and use it in GitHub Desktop.
Compare base64 encoding binary and original string binary
import base64
import sys
# From https://en.wikipedia.org/wiki/Base64
# A = 0 (whereas ord('A') = 65)
# a = 26 (whereas ord('a') = 97)
# 0 = 52
def base64index(char):
if len(char) > 1:
raise Exception('Only one character can be passed in to base64index')
if char == '+' or char == '-':
return 62
if char == '/' or char == '_':
return 63
if char.isupper():
return ord(char) - 65
if char.islower():
return ord(char) - 71
if char.isnumeric():
return 52 + int(char)
def base64rep(char):
if char == "=":
return "PADDED"
return '{:06b}'.format(base64index(char))
def binaryrep(bytes):
return '{:08b}'.format(int(bytes.hex(), 16))
def base(seq):
return "".join([base64rep(char) for char in seq])
def printBase(encoded):
print(" ".join([char for char in encoded]))
print(base(encoded))
def printExplanation(encoded):
decoded = base64.b64decode(bytes(encoded, 'utf-8'))
print(binaryrep(decoded))
print(" ".join([str(char) for char in decoded]))
def printBoth(encoded):
printBase(encoded)
printExplanation(encoded)
printBoth(sys.argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment