Binary Data


Working with Binary Data

The base64 module contains functions for translating binary data into a subset of ASCII suitable for transmission using plaintext protocols.

Super set of binascii and struct

Almost a wrapper around struct and binascii. Implementation can be found at /usr/lib/python3.5/base64.py


In [1]:
import base64

In [2]:
string = 'SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t'
decode_string = base64.b64decode(string)
decode_string.decode('ascii')


Out[2]:
"I'm killing your brain like a poisonous mushroom"

Encodings

  • base32 - uses a smaller subset then base64 Usually the alphabet [A-Z] and [2-7]
  • use b32encode/b32decode to convert bytes objects to convert an ascii string to base32 encoded data or base32 encoded data back to ascii
  • usually don't use bytes-like object, regular strings so we need to encode the raw string into a bytes-like object
  • NOTE: blocks of 10bytes for proper padding, dunno why
  • NOTE: for decoding, blocks of 8bytes.

In [3]:
# this wont work:string = 'this is a regular ascii string that we will convert to base32'
string = string.encode('utf-8')
print(len(string))
base64.b32encode(string)


64
Out[3]:
b'KNJWI5CJI52HAYSHPBYGE3LDM5SVOOJRMNUUE2LDNVDHAYTJIJZWCV3UNREUORLHMNDTS4DDGI4XKYRTKZ5ESRZRGFRTE2DZMIZDS5A='

In [ ]:


In [ ]: