Astrum
Astrum

Reputation: 621

XOR cipher in python - odd length string

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).

Upvotes: 1

Views: 389

Answers (2)

Astrum
Astrum

Reputation: 621

I was having problems because I implemented the cipher incvorecctly. The way to do it would be just:

def xor_cipher(s, hexkey):
    key = ''
    for i,j in zip(s, cycle(hexkey)):
        key += j
    return hex(int(s,16)^int(key,16))[2:]

which clears up all the problems right there.

Upvotes: 2

Jaroslaw Matlak
Jaroslaw Matlak

Reputation: 574

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)

Upvotes: 1

Related Questions