1

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

Astrum
  • 591
  • 3
  • 12
  • 25

2 Answers2

2

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.

Astrum
  • 591
  • 3
  • 12
  • 25
1

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)
Jaroslaw Matlak
  • 574
  • 1
  • 12
  • 23
  • That did produce a result, although I have no idea why. Could you explain what you did? Does the rest of my code seem sound? Also, I forgot to mention this is python 3. – Astrum Nov 18 '16 at 11:42
  • It works mostly correct, although there seems to be some small problem. When using the correct decryption key, it produces "b"\x03ooking MC's like a pound of bacon"" instead of "b'cooking MC's...". Any idea why? – Astrum Nov 18 '16 at 12:09
  • @Astrum Try to add `'0x'` at the begining of the deciphred code (e.g: `code='0AB9C0'; decode('0x'+code);` ). If it doesn't work - post the decryption code and I'll find out what's wrong :) – Jaroslaw Matlak Nov 18 '16 at 15:05
  • Yeah, it still causes a problem. Python 3 won't accept a hex string with 0x in front of it, it seems. Take something simple like the hex string '130e5a0d1b095a1b5a1e1b08115a1b141e5a090e150817035a14131d120e'. The key is 211 in base 10 but it produces "b'\tt was a dark and stormy night' " instead of "b'it was a dark...". It looks like the first bit of the original string is not being XORed. – Astrum Nov 20 '16 at 07:53