pythonpython-3.xbase64binary-databinascii

Python string with binary data base64 encode gives TypeError


Im struggling with the following issue:

I have an array with the following binary data (after encryption):

data = '\x03×ÿ\x7f*J\x9aÖ¯AÀM|ü{R2+M°ø2\x83.\x1f@µ³U¡VT'

I want to base64 encode it.

When I do

binascii.b2a_base64(data)

I'm getting TypeError: a bytes-like object is required, not 'str'

I desperately need an advice how to deal with this kind of data. Please help!

Update: i fixed data type, ofcourse - my issue is related to the single string


Solution

  • You don't have binary data, you have text strings.

    Convert the text to bytes first; you can do so by encoding. It looks as if you produced Unicode codepoints that correspond one-on-one with Latin-1 bytes, so you could encode to that codec:

    for value in array:
        bytes_value = value.encode('latin-1')
        base64_encoded = binascii.b2a_base64(bytes_value)
    

    However, what encoding is appropriate for your text depends on the way it was produced in the first place. If you are encrypting, you may want to fix your encryption code to not produce text but bytes directly.