Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

base64.encodestring failing in python 3

The following piece of code runs successfully on a python 2 machine:

base64_str = base64.encodestring('%s:%s' % (username,password)).replace('\n', '')

I am trying to port it over to Python 3 but when I do so I encounter the following error:

>>> a = base64.encodestring('{0}:{1}'.format(username,password)).replace('\n','')
Traceback (most recent call last):
  File "/auto/pysw/cel55/python/3.4.1/lib/python3.4/base64.py", line 519, in _input_type_check
    m = memoryview(s)
TypeError: memoryview: str object does not have the buffer interface

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/auto/pysw/cel55/python/3.4.1/lib/python3.4/base64.py", line 548, in encodestring
    return encodebytes(s)
  File "/auto/pysw/cel55/python/3.4.1/lib/python3.4/base64.py", line 536, in encodebytes
    _input_type_check(s)
  File "/auto/pysw/cel55/python/3.4.1/lib/python3.4/base64.py", line 522, in _input_type_check
    raise TypeError(msg) from err
TypeError: expected bytes-like object, not str

I tried searching examples for encodestring usage but not able to find a good document. Am I missing something obvious? I am running this on RHEL 2.6.18-371.11.1.el5

like image 818
Vinay Pai Avatar asked Jun 30 '15 17:06

Vinay Pai


People also ask

How do you check whether the string is base64 encoded or not in Python?

All you need to do is decode, then re-encode. If the re-encoded string is equal to the encoded string, then it is base64 encoded. That's it!

What is B in base64?

That b simply means you are taking input as a bytes or bytes array not as a string.


1 Answers

You can encode() the string (to convert it to byte string) , before passing it into base64.encodestring . Example -

base64_str = base64.encodestring(('%s:%s' % (username,password)).encode()).decode().strip()
like image 106
Anand S Kumar Avatar answered Sep 18 '22 16:09

Anand S Kumar