Astrum - 1 month ago 15

Python Question

I'm trying to make a cipher using the xor operator. Right now this is what I have:

`from binascii import hexlify, unhexlify`

from itertools import cycle

s = '636174'

key = '13'

def cipherkey(s, key):

bin_key = bin(int(key))[2:]

bin_s = bin(int(s, 16))[2:]

k = []

if len(bin_key) < len(bin_s):

for i, j in zip(cycle(bin_key), bin_s):

k.append('{}'.format(i))

else:

for i, j in zip(bin_key, cycle(bin_s)):

k.append('{}'.format(i))

return int("".join(k),2)

def xor_cipher(s,key):

n = cipherkey(s, key)

out = n ^ int(s,16)

return hex(out)

print(unhexlify(xor_cipher(s, key)))

I'm sure this is super inefficient code, but I'd like to keep as much of it as possible. I've startched my head over this for a while now and haven't found the mistake.There must be a mistake in how I'm iterating over

`zip(cycle(bin_key), bin_s)`

Answer

Try to replace the last line:

```
print(unhexlify(xor_cipher(s, key)))
```

with this code:

```
res=xor_cipher(s, key)[2:] # remove '0x' from the begining of the hex code
if res.__len__()%2 ==1: # if res length is odd,
res="0{}".format(res) # append '0' at the begining to make it even
print unhexlify(res)
```