user7768426
user7768426

Reputation:

Python 3.6 File Decryption with XOR

I've written a bit of code that works great in encrypting a file, however I do not know how to decrypt it. Could someone explain to me how to decry the encrypted file? Thanks.

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'))

Upvotes: 5

Views: 7873

Answers (2)

AChampion
AChampion

Reputation: 30258

To decrypt a 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'

Upvotes: 6

Raymond Hettinger
Raymond Hettinger

Reputation: 226316

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

Upvotes: 2

Related Questions