-
Notifications
You must be signed in to change notification settings - Fork 0
/
germain.py
64 lines (59 loc) · 1.84 KB
/
germain.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
""" germain.py approximates the number of safe primes """
import os
import sys
import time
import socket
import base64
import msgpack
import multiprocessing
import gmpy
import Crypto
import Crypto.Random
import Crypto.Util.number as number
def count_safe_primes(bits):
randfunc = Crypto.Random.new().read
started = time.time()
ret = []
while True:
r = gmpy.mpz(number.getRandomNBitInteger(bits-1, randfunc))
q = gmpy.next_prime(r)
p = 2*q + 1
germain = gmpy.is_prime(p)
ret.append((germain, int(q - r)))
if time.time() - started > 60:
break
return ret
def main():
sleep_time = 0.1
while True:
try:
s = socket.socket()
s.connect(('sw.w-nz.com', 19102))
wfile = s.makefile('w')
unpacker = msgpack.Unpacker()
sleep_time = 0.1
if len(sys.argv) >= 2:
client = sys.argv[1]
else:
client = base64.b64encode(os.urandom(5))
while True:
try:
bits = unpacker.unpack()
except msgpack.OutOfData:
tmp = s.recv(4096)
if not tmp:
break
unpacker.feed(tmp)
continue
res = count_safe_primes(bits)
print bits, len(res)
wfile.write(msgpack.dumps([client, bits, res]))
wfile.flush()
except socket.error as e:
print "%s. sleeping %s" % (e, sleep_time)
time.sleep(sleep_time)
sleep_time = min(sleep_time * 2, 60)
if __name__ == '__main__':
for i in xrange(multiprocessing.cpu_count()):
print 'starting process #%s' % (i+1)
multiprocessing.Process(target=main).start()