How to Encode a String into Into Base64 in Python

The aim of this page📝 is to provide simple steps for using the base64 module in Python for encoding and decoding to/from base64 strings.

Pavol Kutaj
2 min readOct 13, 2022

The current standard (RFC4648) states this is useful when

  • It stores or transfers data in environments restricted to ASCII
  • It makes it possible to manipulate binary objects with text editors
  • In the context of web development, it is often used for JSON transformation/encoding, mainly when it’s required to pass it as a query string (i.e. in the browser’s address bar)
  • I am in the context of infrastructure-as-code, and my story is still a bit different.
  • I am using base64 due to restrictions enforced by the automation platform, which it boils down to the fact that the configuration objects (in JSON, but you can think of any other, too) must be passed into the platform as a single parameter.
  • The platform (layers of interconnected scripts) decodes that base64 config object and only then works to call proper functions with their respective signatures
  • What follows is Python-specific

BASH VS PYTHON

  • the essential point is that the encoding happens on the <bytes> class and that the base64 methods will not accept <string>
  • → you’ll get a TypeError if you simply try to encode a string
  • …all that I need for my use case is precisely that
>>> from base64 import b64encode

>>> b64encode("foo")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\users\admin\appdata\local\programs\python\python38-32\lib\base64.py", line 58, in b64encode
encoded = binascii.b2a_base64(s, newline=False)
TypeError: a bytes-like object is required, not 'str'

a bytes-like object is required, not 'str'
  • however, in Ubuntu bash, the base64 the module accepts strings just fine, so why bother right?
~$ echo "foo" | base64
Zm9vCg==
~$

WHY BOTHER?

  • because I want to know
  • …and I need this as part of my CLI app that composes complex commands
  • these are the steps to encode a string into base64 value in Python
>>> from base64 import b64encode,b64decode
>>> s = "foo"
>>> s_bin = s.encode("ascii")
b'foo'
>>> s64_bin = b64encode(s_bin)
b'Zm9v'
>>> s64 = s64.bin.decode()
'Zm9v'
# yeah, i'm a programmer

--

--

No responses yet