python-3.xunicodebyteaescbc-mode

Python 3 CBC fail because of double backslash byte


I am trying to read back ciphertext in a file, for example, \t"\x87]\xb6^,\xa7G\xf7\x99<\xb2-\x06\xc8 however when I make it a bytearray for CBC decryption, I get b'\\t"\\x87]\\xb6^,\\xa7G\\xf7\\x99<\\xb2-\\x06\\xc8' which ultimately fails as this is not a 16 byte multiple for CBC to decrypt. I have tried decoding with unicode escape, however it doesn't retain it's data type as a byte. I cannot seem to work out how to get this to decrypt normally again?

Thanks.


Solution

  • For everyone with this issue:

    If you are writing ciphertext to a file that contains a \, instead of reading it as a string and converting to bytes (which adds an extra \ escape character), use the "b" modifier in the open() statement.

    Example: with open("test.txt","rb") - notice the b? That means everything from the file is automatically read as a byte. Don't write or deal with strings. Write and read bytes directly and then your encrypt/decrypt functions will now work. No extra \.