使用XOR进行Python 3.6文件解密

5 python encryption xor python-3.x

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

码:

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'))
Run Code Online (Sandbox Code Playgroud)

ACh*_*ion 6

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

>>> 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'
Run Code Online (Sandbox Code Playgroud)