python help needed
I'm trying to make a program that will xor a file with a preset key (and do some more minor stuff) and then save it as a .jpg.
I got a working program now, but the problem is it only does it for the first 1156 bytes (and doing it right), like the rest isn't there (the original file is 20kB in size).
So here's the code :
# xoring a file with string 'secret'
from operator import xor
key = list('secret')
for i in range (6) :
key[i] = ord(key[i])
index = 0
f = open ('data.bin')
g = open ('xored.jpg', 'w')
data = list(f.read())
f.close()
for i in range (20426) :
hex = ord(data[i])
if index==6 :
index = 0
rez = xor (hex, key[index])
if rez == 23 :
rez = 0
elif rez == 0 :
rez = 23
elif rez == 78 :
rez = 66
elif rez == 66 :
rez = 78
elif rez == 36 :
rez = 144
elif rez == 144 :
rez = 36
rez = chr (rez)
index = index + 1
g.write (rez)
g.close()
Any help is welcome, and so are suggestions on optimizing my programing.
for i in range (20426): Maybe I'm misunderstanding something here, but if this is tracing through the file, you're only going through the first 2KB. Since data is a list, you could do this instead to ensure all data is modified: for i in data:
Also, importing xor from operator and using that as a method is unnecessary. The xor operator is built in, you use the ^ symbol:
>>> ord('d') 100 >>> ord('a') 97 >>> 100^97 5 >>> from operator import xor >>> xor(100, 97) 5
Also, instead of looping through your list and applying ord to it, you could just use the built in map function:
map(ord, key)
ynori7 wrote: [quote]for i in range (20426): Maybe I'm misunderstanding something here, but if this is tracing through the file, you're only going through the first 2KB. Since data is a list, you could do this instead to ensure all data is modified: for i in data: [/quote]
Actually it's 20kB but yes, you're right about the alternative, it is better.
ynori7 wrote: Also, importing xor from operator and using that as a method is unnecessary. The xor operator is built in, you use the ^ symbol: [quote]>>> ord('d') 100 >>> ord('a') 97 >>> 100^97 5 >>> from operator import xor >>> xor(100, 97) 5
Also, instead of looping through your list and applying ord to it, you could just use the built in map function:
map(ord, key) [/quote]
This is some stuff I didn't know. I'm glad someone told me about it, and I'm of to do some research on map. Thanks for your help.