+4  A: 

You can use the extended Euclidean algorithm to solve for d in the congruence

de = 1 mod phi(m)

For RSA encryption, e is the encryption key, d is the decryption key, and encryption and decryption are both performed by exponentiation mod m. If you encrypt a message a with key e, and then decrypt it using key d, you calculate (ae)d = ade mod m. But since de = 1 mod phi(m), Euler's totient theorem tells us that ade is congruent to a1 mod m -- in other words, you get back the original a.

There are no known efficient ways to obtain the decryption key d knowing only the encryption key e and the modulus m, without knowing the factorization m = pq, so RSA encryption is believed to be secure.

Jim Lewis
I had good luck with the code from here: http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Recursive_method_2Simply inputting a=e, b=phi to that function gives me x,y - y is discarded, and x is the secret exponent d !
Chris
@Chris: It's a pity Euler and Euclid didn't survive to collect their share of the patent revenue. So long, and thanks for all the math!
Jim Lewis
Just for completeness, another way to do the computation with the same basic performance is d = e**(phi(phi(m))-1) mod phi(m).
GregS
@GregS: The identity holds, but I disagree that the performance is comparable. Finding an inverse mod n with Euclid's algorithm can be done in O(log n) time. But finding phi(n) is as difficult as factoring n, for which there is no known O( (log n)^k ) algorithm for any k. And if the original p and q are well-chosen, (p-1) and (q-1) will themselves have large prime factors, making phi(phi(m)) difficult to calculate.
Jim Lewis
@Jim: Agreed, you have to know phi(phi(m)) or it is pointless. If p-1=2*p' and q-1=2*q', where p' and q' are primes, then phi(phi(m)) is 2*p'*q'. Such a p and q are called safe primes and are common (although unnecessary) in RSA implementations.
GregS
@GregS: Aren't you mixing safe primes with strong primes here? E.g. ANSI requires strong primes (i.e. both p-1 and p+1 must have a large prime factor). Safe primes prevent Pollard's p-1 factoring algorithm but (in principle) not Williams p+1 algorithm. (And, yes, neither using safe nor strong primes is necessary).
abc
@abc: No. In the above, p and q are safe primes, not strong primes.
GregS
@GregS: I'm sorry. I didn't want to imply that you don't know what a safe prime is. Rather, that safe primes are not that common in RSA keys. I've seen crypto libraries that generate strong primes during the RSA key generation, but I'm not aware of a library that uses safe primes.
abc
@abc: Oh, I see. Well, let's look around and check. A strong prime can also be a safe prime, i.e. if the large prime factor of p-1 happens to be (p-1)/2.
GregS