def generate_private_key(phiN):
     e = randrange(phiN//2 + 1, phiN-1)
     g, _, _ = num.extended_gcd(e, phiN)
     while g != 1:
         e = randrange(phiN//2 + 1, phiN-1)
         g, _, _ = num.extended_gcd(e, phiN)
     return e
    def generate(digits=10):
        """
        Creates an RSA encryption system object

        Parameters
        ----------
        digits : The number of digits N should have

        Returns
        -------
        RSA: The RSA system containing:
        * The public key (N,e)
        * The private key (N,d)
        """

        # generate p,q
        N = -1
        while N < 10**digits or N > 10**(digits + 1):
            p = number_theory_functions.generate_prime(digits // 2 + 1)
            q = number_theory_functions.generate_prime(digits // 2)
            if p is None or q is None:
                continue
            N = p * q

        phi = (p - 1) * (q - 1)
        gcd = -1
        e = 1
        while gcd != 1:
            e = randrange(1, phi)
            gcd, a, b = number_theory_functions.extended_gcd(e, phi)

        d = number_theory_functions.modular_inverse(e, phi)

        return RSA((N, e), (N, d))
    def encrypt(self, m):
        """
        Encrypts the plaintext m using the RSA system

        Parameters
        ----------
        m : The plaintext to encrypt

        Returns
        -------
        c : The encrypted ciphertext
        """
        if m is None:
            return None
        gcd, a, b = number_theory_functions.extended_gcd(
            self.private_key[0], m)
        if gcd != 1:
            return None

        return number_theory_functions.modular_exponent(
            m, self.public_key[1], self.private_key[0])
Beispiel #4
0
 def test_extended_gcd(self):
     values = [(119952, 34425, 153), (428848, 123075, 547), (-39, 3, 3)]
     for (a, b, d) in values:
         (gcd, x, y) = number_theory_functions.extended_gcd(a, b)
         self.assertEqual(d, gcd)
         self.assertEqual(gcd, a * x + b * y)
Beispiel #5
0
        self.assertIsNone(
            number_theory_functions.modular_inverse(119952, 34425))


class TestRSA(unittest.TestCase):
    def test_encrypt_decrypt(self):
        rsa = RSA.generate(10)
        plaintexts = [123456789, 17, 9999, 102930]
        for M in plaintexts:
            C = rsa.encrypt(M)
            MM = rsa.decrypt(C)
            self.assertEqual(M, MM)


if __name__ == '__main__':
    a = 5279
    b = -797
    r = lambda x: 1 * x
    d, x, y = map(r, number_theory_functions.extended_gcd(a, b))
    print(f"{d} = {x}a + {y}b ")
    print(
        f"Iron man will give  {x} million bills and loki will give back {y} coins"
    )
    N = 12215009
    e = 3499
    d = 5425399
    rsa = RSA((N, e), (N, d))
    m = 42
    print(rsa.decrypt(rsa.encrypt(m)))
    unittest.main()