forked from JeremyRubin/xkcd-hashing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
executable file
·78 lines (70 loc) · 2.08 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/env python3
import multiprocessing, signal, time, skein, random, string, urllib.request, urllib.parse
try:
import gmpy
except ImportError:
gmpy = None
TARGETSTR = '5b4da95f5fa08280fc9879df44f418c8f9f12ba424b7757de02bbdfbae0d4c4fd' + \
'f9317c80cc5fe04c6429073466cf29706b8c25999ddd2f6540d4475cc977b87f4757be' + \
'023f19b8f4035d7722886b78869826de916a79cf9c94cc79cd4347d24b567aa3e2390' + \
'a573a373a48a5e676640c79cc70197e1c5e7f902fb53ca1858b6'
if gmpy is not None:
TARGET = gmpy.mpz(TARGETSTR, 16)
else:
TARGET = int(TARGETSTR, 16)
RANDOM_BIT_LEN = 512
def init_worker():
signal.signal(signal.SIGINT, signal.SIG_IGN)
def submit(word):
url = "http://almamater.xkcd.com/?edu=mit.edu"
data = urllib.parse.urlencode({'hashable': word})
binarydata = data.encode('ascii')
urllib.request.urlopen(url, binarydata)
def run_worker(do_submit=True, time_limit=None):
best = float('inf')
guess = random.getrandbits(RANDOM_BIT_LEN)
t = time.time()
i = 0
while True:
if gmpy is not None:
encoded = gmpy.digits(guess, 62).encode('ascii')
digest = gmpy.mpz(skein.skein1024(encoded).digest()[::-1] + b'\0', 256)
diff = gmpy.hamdist(digest, TARGET)
else: # fallback implementation
encoded = hex(guess)[2:].encode('ascii')
digest = int(skein.skein1024(encoded).hexdigest(), 16)
diff = bin(digest ^ TARGET).count('1')
if diff < best:
best = diff
if do_submit:
submit(guess)
print('Found new best input with diff [%.3d]: \"%s\"' %
(diff, guess))
i += 1
if time_limit and time.time() - t > time_limit:
break
guess += 1
return i
def main():
cpus = multiprocessing.cpu_count()
pool = multiprocessing.Pool(cpus, init_worker)
for i in range(cpus):
pool.apply_async(run_worker)
try:
while True:
time.sleep(100)
except KeyboardInterrupt:
print('Terminating...')
pool.terminate()
pool.join()
else:
print('Quitting...')
pool.close()
pool.join()
if __name__ == '__main__':
import sys
if len(sys.argv) > 1 and sys.argv[1] == 'time':
iters = run_worker(do_submit=False, time_limit=1)
print('Processed', iters, 'guesses in 1 second')
else:
main()