1
1
"""
2
2
RSA class.
3
3
"""
4
- from math import lcm , ceil
4
+ from math import ceil
5
5
from typing import Tuple
6
+ import json
6
7
7
- from Random import Random
8
+ from MathUtils import MathUtils
8
9
9
10
10
11
class RSA :
@@ -18,15 +19,15 @@ class RSA:
18
19
19
20
def __init__ (self , bit_count : int = 1024 ) -> None :
20
21
# Get 2 large prime numbers, p and q
21
- p : int = Random .get_random_prime (bits = bit_count )
22
- q : int = Random .get_random_prime (bits = bit_count )
22
+ p : int = MathUtils .get_random_prime (bits = bit_count )
23
+ q : int = MathUtils .get_random_prime (bits = bit_count )
23
24
# Calculate n = p * q
24
25
n : int = p * q
25
26
# Get totient function of n, which looks like: λ(n)
26
27
# All of the math is explained on the linked Wikipedia
27
28
# page, but the takeaway is: λ(n) = lcm(p − 1, q − 1)
28
29
# FIXME: THIS ONLY WORKS ON Python 3.9
29
- n_totient : int = lcm (p - 1 , q - 1 )
30
+ n_totient : int = MathUtils . lcm (p - 1 , q - 1 )
30
31
# Get value for e (not to be mistaken for Euler's irrational number, which is equal to 2.718...)
31
32
e : int = 65537 # FIXME: THIS ONLY WORKS IF n_totient is larger than 65537
32
33
# Calulate d as the modular multiplicative inverse of e modulo λ(n)
@@ -88,3 +89,12 @@ def __int_to_string(data: int) -> str:
88
89
:return: Integer to String
89
90
"""
90
91
return data .to_bytes (ceil (data .bit_length () / 8 ), byteorder = 'big' ).decode ()
92
+
93
+ @staticmethod
94
+ def serialize_pub_key (key : Tuple [int , int ]) -> bytes :
95
+ return json .dumps ({"e" : key [0 ], "m" : key [1 ]}).encode ("utf-8" )
96
+
97
+ @staticmethod
98
+ def deserialize_pub_key (data : bytes ) -> Tuple [int , int ]:
99
+ pub_dict = json .loads (data .decode ("utf-8" ))
100
+ return pub_dict ["e" ], pub_dict ["m" ]
0 commit comments