0

I am trying to serialize a bytes object - which is an initialization vector for my program's encryption. But, the Google Protocol Buffer only accepts strings. It seems like the error starts with casting bytes to string. Am I using the correct method to do this? Thank you for any help or guidance!

Or also, can I make the Initialization Vector a string object for AES-CBC mode encryption?

Code

  • Cast the bytes to a string
    • string_iv = str(bytes_iv, 'utf-8')
  • Serialize the string using SerializeToString():
    • serialized_iv = IV.SerializeToString()
  • Use ParseToString() to recover the string:
    • IV.ParseFromString( serialized_iv )
  • And finally, UTF-8 encode the string back to bytes:
    • bytes_iv = bytes(IV.string_iv, encoding= 'utf-8')

Error

string_iv = str(bytes_iv, 'utf-8') UnicodeDecodeError: 'utf-8' codec can't decode byte 0x9b in position 3: invalid start byte

0

1 Answer 1

1

If you must cast an arbitrary bytes object to str, these are your option:

  • simply call str() on the object. It will turn it into repr form, ie. something that could be parsed as a bytes literal, eg. "b'abc\x00\xffabc'"
  • decode with "latin1". This will always work, even though it technically makes no sense if the data isn't text encoded with Latin-1.
  • use base64 or base85 encoding (the standard library has a base64 module wich covers both)
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.