Skip to content

Commit db61ee1

Browse files
committed
readme
1 parent 3e5f58f commit db61ee1

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed
+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import gmpy2, random
2+
from gmpy2 import isqrt, c_div
3+
# Adapted from Hack.lu 2014 CTF
4+
5+
urandom = random.SystemRandom()
6+
7+
def get_prime(size):
8+
while True:
9+
r = urandom.getrandbits(size)
10+
if gmpy2.is_prime(r): # Miller-rabin
11+
return r
12+
13+
def test_key(N, e, d):
14+
msg = (N - 123) >> 7
15+
c = pow(msg, e, N)
16+
return pow(c, d, N) == msg
17+
18+
def create_keypair(size):
19+
while True:
20+
p = get_prime(size // 2)
21+
q = get_prime(size // 2)
22+
if q < p < 2*q:
23+
break
24+
25+
N = p * q
26+
phi_N = (p - 1) * (q - 1)
27+
28+
# Recall that: d < (N^(0.25))/3
29+
max_d = c_div(isqrt(isqrt(N)), 3)
30+
max_d_bits = max_d.bit_length() - 1
31+
32+
while True:
33+
d = urandom.getrandbits(max_d_bits)
34+
try:
35+
e = int(gmpy2.invert(d, phi_N))
36+
except ZeroDivisionError:
37+
continue
38+
if (e * d) % phi_N == 1:
39+
break
40+
assert test_key(N, e, d)
41+
42+
return N, e, d, p, q

README.md

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Code for blog entries.
2+

0 commit comments

Comments
 (0)