Hack This Site - Programming - Unscramble the words

Wed, Jun 30, 21

Welcome back to my walkthrough of hackthissite.org’s CTF missions. I will be going through my thought process of how I solved these missions, and therefore also giving away the solutions. If you came across this to give you hints, watch out for spoilers! Good luck, have fun.

This mission gives us 30 seconds to unscramble a set of words, and return that set in the same order, given a wordlist of possible candidate words. The following code is what I wrote in python3 in order to complete this mission:

def extractScrambledWords():
    """
    Returns a list of the scrambled words.
    """
    targetWords = list()
    with open("targetwords.txt", 'r') as f:
        targetWords = f.readlines()
    targetWords = list(map(lambda word: word.replace("\n", ""), targetWords))
    return targetWords

def unscrambleWords(scrambledWords):
    """
    Returns a list of the unscrambled words.
    """
    # to save IO cost & memory, I will iterate through the wordlist and
    # try to match against the scrambled words
    res = [None] * len(scrambledWords)
    with open("wordlist.txt", 'r')as f:
        for line in f:
            unscrambled = line.replace("\n", "")
            for i in range(len(scrambledWords)):
                unscrambledCopy = unscrambled
                scrambled = scrambledWords[i]
                if len(unscrambled) == len(scrambled):
                    for c in scrambled:
                        index = unscrambledCopy.find(c)
                        if (index > -1):
                            unscrambledCopy = unscrambledCopy[:index] + unscrambledCopy[index+1:]
                    if (len(unscrambledCopy) == 0):
                        res[i] = unscrambled
                        break
    return res

if __name__ == "__main__":
    scrambledWords = extractScrambledWords()
    result = unscrambleWords(scrambledWords)
    print(','.join(result))

The generated scrambled set is different every time, so you would have to quickly switch out targetwords.txt file with the new scrambled words.