There is a code in php:

$newmsg = $newmsg . ($message[$i] ^ $key[$i % $kl]); 

What will it look like in python? Supposed so, but did not work:

 newmsg+=str(msg[i]) or str(key[i % kl]) 

2 answers 2

Assuming that you want to translate the entire cycle to Python, and not just one iteration corresponding to the index i , then perform the XOR of each byte of the specified string with the given key in Python 3:

 from itertools import cycle def xor(message, key): return bytes(a^b for a, b in zip(message, cycle(key))) 

Example:

 >>> key = b'key' >>> xor(b'hello world', key) b'\x03\x00\x15\x07\nY\x1c\n\x0b\x07\x01' >>> xor(_, key) # и обратно b'hello world' 

It should be noted that if you do XOR for encryption, then the key ( key ) must have a length not less than the message itself ( message ) and not be used more than once.

    Something like this should be:

     newmsg += chr(ord(msg[i]) ^ ord(key[i % kl]))