I have a problem with decoding bytes to string in python. I wanted to crack the single-byte xor cipher by brute-forcing it. And I did. The key was 90
(dec). The problem here is, that I actually could XOR every byte with a number > 127
but then I always got UnicodeError
, when I wanted to decode it. They all looked the same, just different bytes:
128. 'utf-8' codec can't decode byte 0x98 in position 0: invalid start byte
def main():
d = base64.b64decode(base64string)
for i in range(1, 255):
try:
output_bytes = b''.join([bytes([b ^ i]) for b in d])
decoded = output_bytes.decode('utf-8')
except UnicodeDecodeError as e:
print(f'{i}. {e}')
pass
if __name__ == '__main__':
main()
I either had to write a try/except
block to prevent my program from failing, or I had to change range(1, 255)
to range(1, 127)
.
Is it an expected behavior? If no, then what am I doing wrong, and if yes, then why? Shouldn't I be able to do xor
and then decode()
no matter which byte I use?