Phillip Sloan
Phillip Sloan

Reputation: 125

Breaking a Repeating-Key XOR Cipher

Challenge #6

Challenge File

In this Cryptopals Challenge that I am currently working on. I have the correct Hamming function and feasible (though possibly incorrect) FindKey and XOR functions.


So far, I have this code...

import base64

def binary(n):
    return '{0:08b}'.format(n)

def Hamm(s1, s2):
    d = 0
    for c1, c2 in zip(s1, s2):
        if c1 != c2:
            b1 = binary(c1)
            b2 = binary(c2)
            for a, b in zip(b1, b2):
                if a != b:
                    d += 1
    return(d)

def FindKey(b64_s):
    key_dict = {}
    low = 9999
    previous = 0
    for size in range(2, 40):
        ham1 = b64_s[previous : size + 1]
        ham2 = b64_s[size + 1 : size * 2 + 1]
        low = Hamm(ham1, ham2)/size
        key_dict = {low : size}
        previous = size
    return(key_dict[low])

def XOR(byte_string):
    result = ''
    key = max(byte_string, key=byte_string.count) ^ ord('e')\
    for b in byte_string:
        result += chr(b ^ key)
    print(result)

# get base64 file
b64_string = ''
with open("TestFile_Challenge06_CSIS463.txt") as f:
    for line in f:
        b64_string = b64_string + str(line)

XOR(base64.b64decode(b64_string))

Upvotes: 1

Views: 956

Answers (1)

Shakkhar
Shakkhar

Reputation: 199

Read what you wrote again:

it is the number of different bits between two strings

What you are doing in your code is taking the total number of characters that are different between the two strings, instead of bits.

I modified your code a little to fix that:

    def Hamm(s1, s2):
    d = 0
    for ch1, ch2 in zip(s1, s2):
        c1 = ord(ch1)
        c2 = ord(ch2)
        while c1 or c2:
            b1 = c1 & 1
            b2 = c2 & 1
            d += b1 ^ b2
            c1 >>= 1
            c2 >>= 1
    return d

Upvotes: 2

Related Questions