Challenge 14


In [2]:
myinput = 'ihaygndm'

Solution 14.1


In [3]:
import hashlib

In [140]:
def repetitions(mystr, n, m):
    ns = []
    ms = []
    i = 0
    j = 0
    while i < len(mystr) - n + 1:
        if mystr[i:i+n] == mystr[i] * n:
            if mystr[i] not in ns:
                ns.append(mystr[i])
            if mystr[i:i+m] == mystr[i] * m:
                if mystr[i] not in set(ms):
                    ms.append(mystr[i])
            i += n
        else:
            i += 1
    return ns, ms

def hashkey(myinput, k):
    mystr = myinput + str(k)
    hsh = hashlib.md5(mystr.encode('utf-8')).hexdigest()
    return hsh
    
def generate_keys(myinput, hashkey_function, n, m):
    white = []
    key_ns = []
    key_ms = []
    k = 0
    while len(white) < 64:
        hsh = hashkey_function(myinput, k)
        ns, ms = repetitions(hsh, 3, 5)
        if len(ns) > 0:
            key_ns.append((k, ns[0]))
        if len(ms) > 0:
            for char in ms:
                key_ms.append((k, char))
            for ns_tuple in key_ns:
                for ms_tuple in key_ms:
                    if (ns_tuple[1] == ms_tuple[1]) and (0 < ms_tuple[0] - ns_tuple[0] < 1001):
                        if ns_tuple[0] not in white:
                            white.append(ns_tuple[0])
        k += 1
    return sorted(white)

In [142]:
sorted_indices1 = generate_keys(myinput, hashkey, 3, 5)

In [143]:
sorted_indices1[63]


15035

Solution 14.2


In [144]:
def hashkey_stretched(myinput, k, n):
    mystr = myinput + str(k)
    hsh = hashlib.md5(mystr.encode('utf-8')).hexdigest()
    for i in range(n-1):
        hsh = hashlib.md5(hsh.encode('utf-8')).hexdigest()
    return hsh

def new_hashkey(myinput, k):
    return hashkey_stretched(myinput, k, 2017)

Test


In [146]:
hashkey_stretched('abc', 0, 2017)


Out[146]:
'a107ff634856bb300138cac6568c0f24'

In [147]:
sorted_indices2 = generate_keys('abc', new_hashkey, 3, 5)

In [148]:
sorted_indices[63]


Out[148]:
22551

Result


In [149]:
sorted_indices3 = generate_keys(myinput, new_hashkey, 3, 5)

In [150]:
sorted_indices3[63]


Out[150]:
19968