Skip to content

Instantly share code, notes, and snippets.

@turtlemonvh
Created July 17, 2019 14:47
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 turtlemonvh/0c20670dd6c7705619a39ecb7b544bcf to your computer and use it in GitHub Desktop.
Save turtlemonvh/0c20670dd6c7705619a39ecb7b544bcf to your computer and use it in GitHub Desktop.
Url-safe Base64 to bitstring

Urlsafe Base64 to bit strings

I have been doing a lot of work with binary protocols (esp. for crytography) that encode ciphertext in base64.

To help with debugging these protocols and data, I wanted something that could show me the ones and zeros associated with a piece of data.

You may be able to use sed, base64, and hexdump to get the same functionality on a unix system, but I didn't mess around with that too much.

Example use

In an iPython shell

In [1]: %paste

In [2]: urlsafeb64_to_bitstring("NX6-")
Out[2]: '00110101 01111110 10111110'

In [3]: s = urlsafeb64_to_bitstring("NX6-")

In [4]: s
Out[4]: '00110101 01111110 10111110'

In [5]: bitstring_to_urlsafeb64(s)
Out[5]: 'NX6-'
import base64
def urlsafeb64_to_bitstring(keyid):
"""Convert a base64 encoded string into a space-separated list of bits for debugging.
"""
s = base64.urlsafe_b64decode(keyid)
bitstring = ""
bts = bytearray(s)
# Iterate over bytes
for bt in bts:
# Iterate over bits, starting at left (high) bits so we build the string left to right
for i in reversed(xrange(8)):
v = bt >> i & 1 # check if bit is set
bitstring += "%d" % (v)
bitstring += " "
return bitstring[:-1] # extra space
def bitstring_to_urlsafeb64(bitstring):
"""Convert a space-separated list of bits into a base64 encoded string.
"""
byte_list = [] # will contain integer representations of each bit
for bitstring_component in bitstring.split(" "):
current_val = 0
for bit in bitstring_component:
# Shift up
current_val = current_val << 1
if bit == "1":
# Set the lowest bit
current_val = current_val | 1
byte_list.append(current_val)
return base64.urlsafe_b64encode(bytearray(byte_list))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment