The reasons why this algorithm works are discussed in the mathematics section. Its security comes from the computational difficulty of factoring large numbers. To be secure, very large numbers must be used for p and q - 100 decimal digits at the very least.
I'll now go through a simple worked example.
1) Generate two large prime numbers, p and qTo make the example easy to follow I am going to use small numbers, but this is not secure. To find random primes, we start at a random number and go up ascending odd numbers until we find a prime. Lets have:
p = 7
2) Let n = pq
n = 7 * 19
3) Let m = (p - 1)(q - 1)
m = (7 - 1)(19 - 1)
4) Choose a small number, e coprime to m
e coprime to m, means that the largest number that can exactly divide both e and m (their greatest common divisor, or GCD) is 1. Euclid's algorithm is used to find the GCD of two numbers, but the details are omitted here.
e = 2 => GCD(e, 108) = 2 (no)
5) Find d, such that de % m = 1
This is equivalent to finding d which satisfies
n = 0 => d = 1 / 5 (no)
To do this with big numbers, a more sophisticated algorithm called extended Euclid must be used.
The message must be a number less than the smaller of p and q. However, at this point we don't know p or q, so in practice a lower bound on p and q must be published. This can be somewhat below their true value and so isn't a major security concern. For this example, lets use the message "6".
C = Pe % n
This works very much like encryption, but involves a larger exponentiation, which is broken down into several steps.
P = Cd % n
We now repeat the sequence of operations that reduced 6265 to 12032 to reduce the exponent down to 1.
= 62 * 3616 % 133
And that matches the plaintext we put in at the beginning, so the algorithm worked!