from itertools import izip, cycle
def xor_crypt_string(data, key):
return ''.join(chr(ord(x) ^ ord(y)) for (x,y) in izip(data, cycle(key)))
my_data = "Hello. This is a secret message! How fun."
my_key= "firefly"
# Do the actual encryption
encrypted = xor_crypt_string(my_data, key=my_key)
# This will obtain the original data from the encrypted
original = xor_crypt_string(encrypted, key=my_key)
Algo más legible:
def xor(fileTarget, key):
fileTarget = fileTarget + os.listdir(fileTarget)[0]
ifile = os.path.split(fileTarget)[0]+"/xor.in"
ofile = os.path.split(fileTarget)[0]+"/xor.out"
os.rename(fileTarget, ifile)
if os.path.isfile(key):
kf = open(key)
keyData = kf.read()
kf.close()
else:
keyData = key
e = open(ofile, "w")
f = open(ifile, "r")
bytesToCopy = os.stat(os.path.split(fileTarget)[0]+"/xor.in")[6]
while bytesToCopy:
if bytesToCopy >= len(keyData):
data = f.read(len(keyData))
bytesToCopy -= len(keyData)
encryptedData = ''.join([chr(ord(data[i])^ord(keyData[i])) for i in xrange(len(data))])
# encryptedData = ''.join(chr(ord(x) ^ ord(y)) for (x,y) in izip(data, cycle(key)))
e.write(encryptedData)
else:
data = f.read(bytesToCopy)
bytesToCopy = 0
encryptedData = ''.join([chr(ord(data[i])^ord(keyData[i])) for i in xrange(len(data))])
# encryptedData = ''.join(chr(ord(x) ^ ord(y)) for (x,y) in izip(data, cycle(key)))
e.write(encryptedData)
os.remove(ifile)
e.close()
f.close()
return os.path.split(fileTarget)[0]+"/xor.out"