From Wikipedia:
Determine d (using modular arithmetic) which satisfies the congruence relation
- Stated differently, ed − 1 can be evenly divided by the totient (p − 1)(q − 1).
- This is often computed using the extended Euclidean algorithm.
- d is kept as the private key exponent.
The extended Euclidean algorithm allows you to find integers such that the following holds:
The extended Euclidean algorithm is particularly useful when a and b are coprime, since x is the modular multiplicative inverse of a modulo b.
In this formula set a
to e
, b
to (p-1)(q-1)
and gcd(a, b)
to 1 (because e and φ(pq) are required to be coprime in the RSA algorithm) and solve for x
which gives you your d
.
The Wikipedia page on extended Euclidean algorithm has more details on how to write the algorithm to solve for x and y. For example you can use this recursive function (in pseudo-code):
function extended_gcd(a, b)
if a mod b = 0
return {0, 1}
else
{x, y} := extended_gcd(b, a mod b)
return {y, x-(y*(a div b))}
In .NET if you just want to generate some RSA keys you don't have to implement the RSA algorithm yourself. There already is an implementation of RSA in the .NET framework that you can use.