socked and bytes operation

Chris Rebert clp2 at rebertia.com
Wed Apr 21 15:01:13 CEST 2010


On Wed, Apr 21, 2010 at 5:37 AM, luca72 <lucaberto at libero.it> wrote:
> Hello i have this question :
> i connect to the server in this way:
> sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
> sock.connect(('192.168.1.11',11502))
> rcv = sock.recv(8124)
> here i get 14 random bytes , in a string with strange chars like :
> ¬¨^.á‹•Ò
> a„ãj
> I think because sock.recv return a string.
> Now i have to xor this 14 bytes with a key stored in file as a sting.
> Can you help me to understand how to do it.

# Disclaimer: Completely untested
from itertools import cycle
f = open("path/to/key_file", 'r') # open file
key = f.read() # read from file
f.close() # close file
# convert strings to lists of integers
rcv = map(ord, rcv)
key = map(ord, key)
plain_chars = []
# do the XOR-ing
for cypher_char, key_char in zip(rcv, cycle(key)):
    plain_char = chr(ord(cypher_char) ^ ord(key_char))
    plain_chars.append(plain_char)
# join decrypted characters into a string
# and output it
print ''.join(plain_chars) # Python idiom

You'll probably need to read up on what zip(), map(), ord(), and chr() do:
http://docs.python.org/library/functions.html

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list