Python 3.6 Decrypting files using XOR

I wrote a bit of code that works great when encrypting a file, however I don't know how to decrypt it. Can anyone explain to me how to condemn an ​​encrypted file? Thank.

Code:

from itertools import cycle

def xore(data, key):
    return bytes(a ^ 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(), b'anykey'))

      

+5


source to share


2 answers


To decrypt the xor encryption, you just need to encrypt it again with the same key:



>>> from io import BytesIO
>>> plain = b'This is a test'
>>> with BytesIO(plain) as f:
...     encrypted = xore(f.read(), b'anykey')
>>> print(encrypted)
b'5\x06\x10\x18E\x10\x12N\x18K\x11\x1c\x12\x1a'
>>> with BytesIO(encrypted) as f:
...     decrypted = xore(f.read(), b'anykey')
>>> print(decrypted)
b'This is a test'

      

+4


source


The xor operation is its own reverse. If you "encrypt" it a second time with the original key, it will restore the plaintext.



+2


source







All Articles