Base64 shenanigans in Python
TypeError: a bytes-like object is required, not 'str'
This error occurs when you try to base64 encode or decode a string instead of an appropriate bytes-like object. This is a common issue and originates from when Python changed some of its string mechanics from version 2 to 3. To solve this, make sure you are handling the casting correctly, summarized below.
Encoding a String using Base64 in Python
You can base64 encode a string in Python by first converting it into its appropriate bytes and then using the
import base64 # This is the string you want to encode to base64 my_string = 'Hello World' # First, encode the string into its respective bytes using the encode method. # This can be set as ascii, uti-8, utf-16, utf-32 my_bytes = my_string.encode('utf-8') # Next, use the base64 encode method to encode the bytes to base64 base64_bytes = base64.b64encode(my_bytes) # Finally, you can convert the bytes to a string again if needed: base64_string = str(base64_bytes) print(base64_string)
You can also take this a step further and eliminate the need to encode the string to bytes by prepending the string with a byte indicator like so:
my_bytes = b'Hello World' base64_string = str(base64.b64encode(my_bytes)) print(base64_string)
Decoding a String using Base64 in Python
Decoding a base64 string works similar to encoding. Just be sure not to mix up strings with byte strings!
import base64 # This is the string you want to decode my_string = 'SGVsbG8gV29ybGQ=' # First, transform the string into its respective bytes my_bytes = my_string.encode('utf-8') # Next, use the base64 decode method to decode the bytes to base64 base64_bytes = base64.b64decode(my_bytes) # Finally, you can convert the bytes to a string again if needed: decoded_string = str(base64_bytes) print(decoded_string)