XOR Python Text Encryption/Decryption
I know there is a built in xor operator that can be imported in Python. I'm trying to execute the xor encryption/decryption. So far I have: def xor_attmpt(): message = raw_in
Solution 1:
Here's a variation of the code example from XOR Cipher Wikipedia article:
def xor(data, key):
return bytearray(a^b for a, b in zip(*map(bytearray, [data, key])))
Example (Python 2):
>>> one_time_pad = 'shared secret'
>>> plaintext = 'unencrypted'
>>> ciphertext = xor(plaintext, one_time_pad)
>>> ciphertext
bytearray(b'\x06\x06\x04\x1c\x06\x16Y\x03\x11\x06\x16')
>>> decrypted = xor(ciphertext, one_time_pad)
>>> decrypted
bytearray(b'unencrypted')
>>> plaintext == str(decrypted)
True
Solution 2:
Code below works both ways and does not need length checking as cycle is used.
from itertools import cycle, izip
cryptedMessage = ''.join(chr(ord(c)^ord(k)) for c,k in izip(message, cycle(key)))
Solution 3:
somecode = 'asdfln3j34tnonfdkjnflksdfnla'
message = 'this is my message'
def str_xor(s1, s2):
return "".join([chr(ord(c1) ^ ord(c2)) for (c1,c2) in zip(s1,s2)])
encoded = str_xor(message, somecode)
# encoded == '\x15\x1b\r\x15L\x07@J^MT\x03\n\x1d\x15\x05\x0c\x0f'
decoded = str_xor(encoded, somecode)
# decoded == 'this is my message'
This is a naive / minimalistic implementation without error checking. Here len(somecode) >= len(message) is required.
Solution 4:
for Python 3
from itertools import cycle
cryptedMessage = ''.join(chr(ord(c)^ord(k)) for c,k in zip(message, cycle(key)))
Post a Comment for "XOR Python Text Encryption/Decryption"