Advent of Code: Day 5 Solution

Hashing through the snow

Today the puzzle was hashing content and finding the first several hashes which started with five 0s. This was rather easy to accomplish.

As always, my code is available on Github

The puzzle input was reyedfim

Part 1:

import hashlib

# Read in the input file.
with open ("input.txt", "r") as myfile:  
    data=myfile.read().replace('\n', '')

n = 0

for i in range(8): # Finding 8 character password  
    valid = False
    while not valid:
        currentInput = data + str(n)
        hashed = hashlib.md5(currentInput).hexdigest()
        if hashed[:5] == '00000':
            valid = True
            print "'" + currentInput + "'\t==> " + hashed[5] + " " + hashed + " " + str(n)

        n += 1

The algorithm here is pretty simple. Starting with n being 0, increment n by one and attempt to hash a salt which was the puzzle input with n. If that MD5 hashed value begins with five 0s, the sixth character is a part of a password which is 8 characters long. I got lazy and did not have it join the parts of the password into the string and it ends up outputting one character of the password at a time.

Solution: f97c354d

Part 2: The second part of the 5th day was to hash and again, if the hash began with five 0s, it was a part of the password. This time though, the character position within the password was indicated by the sixth character of the hash and the seventh character was the actual password piece. This provided the following code:

import hashlib

# Read in the input file.
with open ("input.txt", "r") as myfile:  
    data=myfile.read().replace('\n', '')

n = 0  
passwordPieces = {}

while len(passwordPieces) < 8: # Finding 8 character password  
    currentInput = data + str(n)
    hashed = hashlib.md5(currentInput).hexdigest()
    if hashed[:5] == '00000':
        char = hashed[6]
        position = hashed[5]
        if position.isdigit() and int(position) < 8 and position not in passwordPieces:
            passwordPieces[position] = char
            print "'" + currentInput + "'\t==> " + char + " @ " + position + " " + hashed
    n += 1

password = []  
print passwordPieces  
for i in range(8):  
    password.append(passwordPieces[str(i)])
print "".join(password)  

Slightly more complicated but still not terrible. The solution for the second part of the challenge was 863dde27