I've been looking at code for a repeating key XOR cipher and I am unable to grasp some of the functionality of the code. From what I understand, each byte of the key should taken with each byte of the string message and the XOR operation should be applied between them. To do this, it would seem that you would just need to iterate for the length of the string, cycling through each byte of the key and applying the XOR operation.
For some reason, the code uses a generator function (inside of another function) to cycle through the key. An instance of the function is made and saved in a variable, which is then zipped together with the list of the byte values of the message and then the XOR operation is applied.
What I don't get is, since this function loops while TRUE
how will the zip function make tuples between every pair of bytes between both lists? Maybe I'm misunderstanding the function of generators, but could this be cleared up?
Here is the function:
def mc_part5():
def cycle_key(key):
idx = 0
while True:
yield ord(key[idx%len(key)])
idx += 1
g = cycle_key('ICE')
s = "Burning 'em, if you ain't quick and nimble\nI go crazy when I hear a cymbal"
hh = bytes(s,'ascii')
xored = bytes([a^b for (a,b) in zip(hh, g)])
c = '0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f'
expected = bytes.fromhex(c)
assert( xored == expected )