Last active
December 2, 2021 18:05
-
-
Save terror/b29f90b0da96d0074ee5f34e07e739a5 to your computer and use it in GitHub Desktop.
Simple RSA implementation in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from math import gcd | |
class ID: | |
def __init__(self, p = 53, q = 59): | |
self.__p = p | |
self.__q = q | |
@property | |
def __phi(self) -> int: | |
return (self.__p - 1) * (self.__q - 1) | |
@property | |
def __d(self) -> int: | |
return pow(self.e, -1, self.__phi) | |
@property | |
def e(self) -> int: | |
for n in range(2, self.__phi): | |
if gcd(n, self.__phi) == 1: | |
return n | |
@property | |
def N(self) -> int: | |
return self.__p * self.__q | |
def encrypt(self, m: int, recipient): | |
return pow(m, recipient.e, recipient.N) | |
def decrypt(self, m: int): | |
return pow(m, self.__d, self.N) | |
def main(): | |
alice = ID() | |
bob = ID(61, 73) | |
original = 20 | |
m = alice.encrypt(original, bob) | |
r = bob.decrypt(m) | |
print(r) | |
assert r == original | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment