RSA Python & Extended Euclidean algorithm to generate the private key. Variable is None
<p>Problem with simple <a href="https://en.wikipedia.org/wiki/RSA_(cryptosystem)" rel="nofollow"><strong>RSA</strong></a> encryption algorithm. <a href="https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm" rel="nofollow"><strong>Extended Euclidean algorithm</strong></a> is used to generate the <strong>private key</strong>. The problem with <code>multiplicative_inverse(e, phi)</code> method. It is used for finding the multiplicative inverse of two numbers. The function does not return private key correctly. It returns <code>None</code> value.</p>

<hr>

<p>I have the following code:</p>

<pre><code>import random

def gcd(a, b):
    while b != 0:
        a, b = b, a % b
    return a

#Euclidean extended algorithm for finding the multiplicative inverse of two numbers
def multiplicative_inverse(e, phi):
    d = 0
    x1 = 0
    x2 = 1
    y1 = 1
    temp_phi = phi

    while e &gt; 0:
        temp1 = temp_phi/e
        temp2 = temp_phi - temp1 * e
        temp_phi = e
        e = temp2

        x = x2- temp1* x1
        y = d - temp1 * y1

        x2 = x1
        x1 = x
        d = y1
        y1 = y

    if temp_phi == 1:
        return d + phi

def generate_keypair(p, q):
    n = p * q

    #Phi is the totient of n
    phi = (p-1) * (q-1)

    #An integer e such that e and phi(n) are coprime
    e = random.randrange(1, phi)

    #Euclid's Algorithm to verify that e and phi(n) are comprime
    g = gcd(e, phi)
    while g != 1:
        e = random.randrange(1, phi)
        g = gcd(e, phi)

    #Extended Euclid's Algorithm to generate the private key
    d = multiplicative_inverse(e, phi)

    #Public key is (e, n) and private key is (d, n)
    return ((e, n), (d, n))


if __name__ == '__main__':
    p = 17
    q = 23

    public, private = generate_keypair(p, q)
    print("Public key is:", public ," and private key is:", private)
</code></pre>

<p>Since the variable <code>d</code> in the following line <code>d = multiplicative_inverse(e, phi)</code> contains <code>None</code> value, then during encryption I receive the following error:</p>

<blockquote>
  <p><strong>TypeError:</strong> unsupported operand type(s) for pow(): 'int', 'NoneType',
  'int'</p>
</blockquote>

<p>Output for the code that I provided in the question:</p>

<blockquote>
  <p>Public key is: (269, 391)  and private key is: (None, 391)</p>
</blockquote>

<hr>

<p><strong>Question:</strong> Why the variable contains <code>None</code> value. How to fix that?</p>

<p>I think that this is a problem:</p>

<pre><code>if temp_phi == 1:
   return d + phi
</code></pre>

<p>This function return some value only under condition that temp_phi is equal to 1, otherwise it will not return any value.</p>

python python-3.x encryption rsa private-key