Skip to content

Commit 85b7039

Browse files
authored
Merge pull request #2 from Xiddoc/dev
Fixed function which only works in Python 3.9 & added serialization
2 parents ea190dc + cf923d9 commit 85b7039

File tree

2 files changed

+25
-6
lines changed

2 files changed

+25
-6
lines changed

Random.py renamed to MathUtils.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,12 @@
22
Random class.
33
"""
44
from random import randint
5+
from math import gcd
56

67
from sympy import isprime
78

89

9-
class Random:
10+
class MathUtils:
1011
"""
1112
Static class for random numbers
1213
and other number operations.
@@ -39,3 +40,11 @@ def is_prime(cls, number: int) -> bool:
3940
"""
4041
# Implement later using Rabin-Miller
4142
return isprime(number)
43+
44+
@staticmethod
45+
def lcm(a, b):
46+
"""
47+
Math.lcm implementation (since not available in 3.8).
48+
:return:
49+
"""
50+
return abs(a*b) // gcd(a, b)

RSA.py

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
"""
22
RSA class.
33
"""
4-
from math import lcm, ceil
4+
from math import ceil
55
from typing import Tuple
6+
import json
67

7-
from Random import Random
8+
from MathUtils import MathUtils
89

910

1011
class RSA:
@@ -18,15 +19,15 @@ class RSA:
1819

1920
def __init__(self, bit_count: int = 1024) -> None:
2021
# 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)
2324
# Calculate n = p * q
2425
n: int = p * q
2526
# Get totient function of n, which looks like: λ(n)
2627
# All of the math is explained on the linked Wikipedia
2728
# page, but the takeaway is: λ(n) = lcm(p − 1, q − 1)
2829
# 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)
3031
# Get value for e (not to be mistaken for Euler's irrational number, which is equal to 2.718...)
3132
e: int = 65537 # FIXME: THIS ONLY WORKS IF n_totient is larger than 65537
3233
# Calulate d as the modular multiplicative inverse of e modulo λ(n)
@@ -88,3 +89,12 @@ def __int_to_string(data: int) -> str:
8889
:return: Integer to String
8990
"""
9091
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

Comments
 (0)