July 16, 2019

Cryptopals Challenges: #4

Cryptopals Challenges: #4

In this challenge we are asked given the problem statement:

One of the 60-character strings in this file has been encrypted by single-character XOR.

Find it.
(Your code from #3 should help.)

The idea behind this problem is to go through each line, find the highest-valued histogram, record the weight value, and find the highest weight of each of the lines.  This approach works because we assume the line we are interested in is the only line which is not filled with garbage.  Therefore, if we find the line which has the highest probability of being an English sentence (frequency weights) we can safely assume that it is the desired line.

The code for this problem is relatively simple, so I will describe the process in words then paste the code at the bottom of this post.

  1. Define variables for the highest-valued string, the plaintext it encodes, and its line number
  2. Open the file in read mode
  3. For each line in the file:
    a. Call the SingleCharXOR() function written for #1-3
    b. If the frequency value from (4) exceeds the highest recorded value, save it
  4. Print the best phrase, line number, and character

In code this looks something like:

#Define variables and open file
value_highest = 0
best_phrase = ""
line_counter = 0
with open('4.txt') as fin:
    #Read each line
    for line in fin:
        #For each ASCII character, compute the single char XOR
        for i in range(128):

            #Compute XOR
            phrase, value = SingleCharXOR(bytes.fromhex(line), i)

            #Check if the value is the highest
            if(value_highest < value):

                #Format string to look pretty
                best_phrase = phrase + "ON LINE {} \nXORED AGAINST: {}" \
                    .format(line_counter, chr(i))
                #Record new highest value
                value_highest = value

        #Increment the line counter
        line_counter += 1

#Print the found string
Full script for challenge #3

When the above code block is executed we find the information we are seeking in the form of, yet another, Vanilla Ice quote:

Now that the party is jumping