Python 3.6 异或文件解密

Python 3.6 File Decryption with XOR

我写了一些代码,可以很好地加密文件,但我不知道如何解密它。有人可以向我解释如何解密加密文件吗?谢谢

代码:

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

要解密异或加密,您只需要用相同的密钥再次加密:

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

xor 运算是它自己的逆运算。如果您 "encrypt" 第二次使用原始密钥,它将恢复明文。