Search code examples
pythonpython-3.xencryptionxor

Getting simple error in Python 3.6 XOR


I am using Python 3.6, and am trying to encrypt a file using XOR. I have a simple bit of code:

from itertools import cycle


def xore(data, key):
    return ''.join(chr(a ^ ord(b)) for (a, b) in zip(data, cycle(key)))

with open('C:\\Users\\saeed\\Desktop\\k.png', 'rb') as encry, open('C:\\Users\\saeed\\Desktop\\k_enc.png', 'wb') as decry:
    decry.write(xore(encry.read(), 'anykey'))

I am getting;

Traceback (most recent call last):
  File "C:/Users/saeed/IdeaProjects/xorencrypt/XORenc.py", line 8, in <module>
    decry.write(xore(encry.read(), 'anykey'))
TypeError: a bytes-like object is required, not 'str'

What does this mean, and how do I fix this? Also is there a way to decrypt the file? Thanks.


Solution

  • Make xore to returns a bytes, instead of str.

    def xore(data, key):
        return bytes(a ^ ord(b) for a, b in zip(data, cycle(key)))
    

    to write to file object open with binary mode.


    BTW, by passing byte literal b'anykey' instead of string literal, you don't need to call ord, because iterating bytes yields ints:

    def xore(data, key):
        return bytes(a ^ b for a, b in zip(data, cycle(key)))
    
    with open('...', 'rb') as encry, open('...', 'wb') as decry:
        decry.write(xore(encry.read(), b'anykey'))
        #                              ^^^^^^^^^ bytes literal