@@ -0,0 +1,1321 @@
+import math%0Afrom PrimeUtils import PrimeUtils%0A%0Aclass PrivKey(object):%0A%09def __init__(self, p, q, n):%0A%09%09self.p = p%0A%09%09self.q = q%0A%09%09self.n = n%0A%09%09self.l = (p - 1) * (q - 1)%0A%09%09self.m = PrimeUtils.modinv(self.l, n)%0A%0Aclass PubKey(object):%0A%09def __init__(self, n):%0A%09%09self.n = n%0A%09%09self.n_sq = n * n%0A%09%09self.g = n + 1%0A%0Aclass PKI(object):%0A%09def __init__(self, pubkey = None, privkey = None):%0A%09%09if pubkey is not None:%0A%09%09%09self.pubkey = pubkey%0A%09%09%09self.privkey = privkey%0A%09%09else:%0A%09%09%09(self.privkey, self.pubkey) = self.gen_keypair()%0A%0A%09@staticmethod%0A%09def gen_keypair(bits = 512):%0A%09%09p = PrimeUtils.get_prime(bits // 2)%0A%09%09q = PrimeUtils.get_prime(bits // 2)%0A%09%09n = p * q%0A%09%09return (PrivKey(p, q, n), PubKey(n))%0A%0A%09def encrypt(self, plain):%0A%09%09while True:%0A%09%09%09r = PrimeUtils.get_prime(int(round(math.log(self.pubkey.n, 2))))%0A%09%09%09if r %3E 0 and r %3C self.pubkey.n:%0A%09%09%09%09cipher = pow(self.pubkey.g, plain, self.pubkey.n_sq) * pow(r, self.pubkey.n, self.pubkey.n_sq) %25 self.pubkey.n_sq%0A%09%09%09%09return cipher%0A%0A%09def decrypt(self, cipher):%0A%09%09if not self.privkey is not None:%0A%09%09%09raise AssertionError('Private key must be exist')%0A%09%09if not self.pubkey is not None:%0A%09%09%09raise AssertionError('Public key must be exist')%0A%09%09pubkey = self.pubkey%0A%09%09privkey = self.privkey%0A%09%09plain = privkey.m * ((pow(cipher, privkey.l, pubkey.n_sq) - 1) // pubkey.n) %25 pubkey.n%0A%09%09return plain%0A

Create PKI.py