简体   繁体   中英

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

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'

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM