Marc Hoffer
Marc Hoffer

Reputation: 61

How to calculate the Modular Multiplicative inverse of a number in the context of RSA encryption?

How to calculate the Modular Multiplicative inverse of a number in the context of RSA encryption?

Upvotes: 6

Views: 15118

Answers (5)

paperhorse
paperhorse

Reputation: 4165

I worked out a an simpler inverse function

def privateExponent(p,q,e):
    totient=(p-1)*(q-1)
    for k in range(1,e):
        if (totient*k+1) % e==0:
            return (totient*k+1)/e
    return -1 # shouldnt get here

The equation d*e=1 (mod totient) can be rewritten as d*e=1+k*totient (for some value of k) and the program just searches for first value of k which makes the equation divisible by e (the public exponent). This will work if e is small (as is usually recommended).

We can move all the bignum operations out of the loop to improve its performance.

def privateExponent(p,q,e):
    totient=(p-1)*(q-1)
    t_mod_e=totient % e
    k=0
    total=1
    while total!=0:
        k+=1
        total=(total+t_mod_e) % e
    return (k*totient+1)/e

It turns out that for e=3, we don't really have to search as the answer is always 2*((p-1)*(q-1)+1)/3

Upvotes: 0

zeykukguz
zeykukguz

Reputation: 1

If You need to calculate w for DSA alghoritm, you can use this:

w = s^-1 mod q

is actually

w = s^(q-2) mod q

See: http://en.wikipedia.org/wiki/Modular_multiplicative_inverse#Using_Euler.27s_theorem

Upvotes: 0

Daniel Gartmann
Daniel Gartmann

Reputation: 13008

Direct Modular Exponentiation

The direct modular exponentiation method, as an alternative to the extended Euclidean algorithm, is as follows:

Source: http://en.wikipedia.org/wiki/Modular_multiplicative_inverse

Upvotes: 3

Use the Extended Euclidean Algorithm, which is significantly faster than direct modular exponentiation in practice.

Upvotes: 3

Bill the Lizard
Bill the Lizard

Reputation: 405675

There are two algorithms explained in detail in the Modular multiplicative inverse Wikipedia article.

Upvotes: 2

Related Questions