0
  1. I have an RSA encrypted message (bytes)
  2. I want to make a string: f'!e {encrypted_message}'
  3. Then I need to encode it so I can send it through socket

I try to decode my message so I can put it in a string, but instead I get this:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc4.

How do I put my message (bytes object) in a string?

2
  • 1
    You have to decode the bytes to a str... but why move to a string if you are just going to encode it? Why not b'!e ' + message? Commented Aug 11, 2021 at 17:33
  • @juanpa.arrivillaga Good question. My answer assumes their socket protocol is text-oriented. Commented Aug 11, 2021 at 17:34

1 Answer 1

2

If you really do need a text (ASCII for the sake of this discussion) string with a !e prefix for your wire protocol, the bullet-proof way to turn any bytes to text is Base64.

Happily, base64.b64encode() returns bytes, so you can use a bytestring and +.

import base64

my_bytes = b'asdf'
bytes_with_prefix_for_the_socket = b'!e ' + base64.b64encode(my_bytes)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.