0

This question is similar to this one here but if I put this into this code like so:

import base64
theone = input('Enter your plaintext: ')
encoded = str(base64.b64encode(theone))
encoded = base64.b64encode(encoded.encode('ascii'))
encoded = encoded[2:]
o = len(encoded)
o = o-1
encoded = encoded[:o]
print(encoded)

it raises this problem:

line 58, in b64encode
encoded = binascii.b2a_base64(s, newline=False)
TypeError: a bytes-like object is required, not 'str'

And then if I remove this line of code:

encoded = base64.b64encode(encoded.encode('ascii'))

then it raises the same error. I'm not sure what to do from here and I would be grateful for any help.

Community
  • 1
  • 1
Manav
  • 29
  • 8
  • What is `s` in your example? – Thom Oct 11 '19 at 14:48
  • Thanks thom that was an error(see edit) but this code still raises the same problems – Manav Oct 11 '19 at 14:52
  • The error message says `binascii.b2a_base64`, but that's not in your code. Please make a [mre] including the error message and traceback – wjandrea Oct 11 '19 at 14:56
  • wjandrea I am not entirely sure why it says ```binascii.b2a_base64``` in the error message. – Manav Oct 11 '19 at 14:59
  • What do you mean by traceback? – Manav Oct 11 '19 at 15:00
  • @Manav The traceback is sort of the history or chain of what function called what function, and where the problem occurred. For more details, see [Exceptions](https://docs.python.org/3/tutorial/errors.html#exceptions) in the Python Tutorial. In your case it looks like the error message is missing a few lines from the top, containing the rest of the traceback – wjandrea Oct 11 '19 at 15:02
  • I just realized `binascii.b2a_base64` is called by `b64encode`, that's why it's in the traceback. – wjandrea Oct 11 '19 at 19:32

1 Answers1

1

You seem to be having problems with bytes and strings. The value returned by input is a string (str), but base64.b64encode expects bytes (bytes).

If you print a bytes instance you see something like

b'spam'

To remove the leading 'b' you need to decode back to a str.

To make your code work, pass bytes to base64.b64encode, and decode the result to print it.

>>> theone = input('Enter your plaintext: ')
Enter your plaintext: Hello World!
>>> encoded = base64.b64encode(theone.encode())
>>> encoded
b'SGVsbG8gV29ybGQh'
>>> print(encoded.decode())
SGVsbG8gV29ybGQh
snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
  • Thanks snakecharmerb that helped me a lot. But I was just wondering why did it say ```binascii.b2a_base64``` in the error text when I did not use the binascii module in my code?(see above question comments) – Manav Oct 11 '19 at 19:27
  • Because the base64 module uses functions imported from the binascii module to do the encoding - https://github.com/python/cpython/blob/master/Lib/base64.py – snakecharmerb Oct 12 '19 at 07:22