Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
goelp14
GitHub Repository: goelp14/easyctf-iv-problems
Path: blob/master/rsa_returns/grader.py
671 views
1
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103,
2
107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227]
3
import math
4
import binascii
5
import os
6
from io import StringIO
7
import binascii
8
9
import random as rdom
10
11
_mrpt_num_trials = 5
12
13
14
def is_probable_prime(n):
15
assert n >= 2
16
# special case 2
17
if n == 2:
18
return True
19
# ensure n is odd
20
if n % 2 == 0:
21
return False
22
# write n-1 as 2**s * d
23
# repeatedly try to divide n-1 by 2
24
s = 0
25
d = n-1
26
while True:
27
quotient, remainder = divmod(d, 2)
28
if remainder == 1:
29
break
30
s += 1
31
d = quotient
32
assert(2**s * d == n-1)
33
34
# test the base a to see whether it is a witness for the compositeness of n
35
def try_composite(a):
36
if pow(a, d, n) == 1:
37
return False
38
for i in range(s):
39
if pow(a, 2**i * d, n) == n-1:
40
return False
41
return True # n is definitely composite
42
43
for i in range(_mrpt_num_trials):
44
a = rdom.randrange(2, n)
45
if try_composite(a):
46
return False
47
48
return True # no base tested showed n as composite
49
50
51
def genBadPrime(k, a, n=39):
52
M = 1
53
for i in range(n):
54
M *= primes[i]
55
return k*M + pow(65537, a, M)
56
57
58
def gen_flag(random):
59
return "".join([random.choice("abcdefghijklmnopqrstuvwxyz1234567890") for _ in range(18)])
60
61
62
def generate_c(random):
63
flag = "easyctf{" + gen_flag(random) + "}"
64
p = 4
65
q = 4
66
while not is_probable_prime(p):
67
k1 = random.randint(69000000000, 130000000000)
68
a1 = random.randint(2400000000000000, 4600000000000000)
69
p = genBadPrime(k1, a1)
70
while not is_probable_prime(q):
71
k2 = random.randint(69000000000, 130000000000)
72
a2 = random.randint(2400000000000000, 4600000000000000)
73
q = genBadPrime(k2, a2)
74
e = 65537
75
n = p * q
76
c = pow(int(binascii.hexlify(str.encode(flag)), 16), e, n)
77
txt = 'n: '+str(n)+'\ne: 65537\nc: '+str(c)
78
return StringIO(txt)
79
80
81
def generate(random):
82
return dict(files={
83
"hardrsa.txt": generate_c(random)
84
})
85
86
87
def grade(random, key):
88
flag = gen_flag(random)
89
if key.find(flag) >= 0:
90
return True, "Correct!"
91
return False, "Nope."
92
93