-
Notifications
You must be signed in to change notification settings - Fork 0
/
rsa_gen.sage.py
45 lines (35 loc) · 1.44 KB
/
rsa_gen.sage.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
# This file was *autogenerated* from the file rsa_gen.sage
from sage.all_cmdline import * # import sage library
_sage_const_16 = Integer(16); _sage_const_0 = Integer(0); _sage_const_2 = Integer(2); _sage_const_1 = Integer(1); _sage_const_100 = Integer(100)
import binascii
def str_to_int(msg):
return int(binascii.hexlify(msg).decode(),_sage_const_16 )
def generate_RSA_key_pair(N):
n = _sage_const_0
p = _sage_const_0
q = _sage_const_0
while n.nbits() != N:
p = random_prime(_sage_const_2 **(N//_sage_const_2 ), lbound = _sage_const_2 **(N//_sage_const_2 -_sage_const_1 ))
q = random_prime(_sage_const_2 **(N//_sage_const_2 ), lbound = _sage_const_2 **(N//_sage_const_2 -_sage_const_1 ))
n = p*q
phi = (p-_sage_const_1 )*(q-_sage_const_1 )
e=_sage_const_0
while true:
e = ZZ.random_element(_sage_const_1 ,phi)
if gcd(e,phi) == _sage_const_1 :
break
d = inverse_mod(e,phi)
return (n,e), (n,d), (p,q)
pub, priv, pq = generate_RSA_key_pair(_sage_const_100 )
def encrypt(m,public):
n = public[_sage_const_0 ]
e = public[_sage_const_1 ]
#print("here:", str_to_int(m))
#print(power_mod(str_to_int(m), e, n))
return power_mod(str_to_int(m), e, n)
def decrypt(c, private):
n = private[_sage_const_0 ]
d = private[_sage_const_1 ]
print(binascii.unhexlify(hex(power_mod(c, d,n))))
print(pub, priv, pq)
decrypt(encrypt("solmaz",pub), priv)