388 http://inventwithpython.com/hacking
Email questions to the author: [email protected]
- break
The second step is calculating a number e which is relatively prime to the product of p – 1 and
q – 1. The while loop on line 26 is an infinite loop. The random.randrange() call on
line 28 returns a random integer (stored in the e variable) and line 29 tests if this random number
is relatively prime to (p - 1) (q - 1). If it is, the break statement on line 30 breaks
out of the infinite loop. Otherwise, the program execution jumps back to line 26 and will keep
trying different random numbers until it finds one that is relatively prime with (p - 1) (q -
1).
This way we can guarantee that when the program execution gets past this while loop, the
variable e will contain a number that is relatively prime to (p - 1) * (q - 1).
makeRsaKeys.py
Step 3: Calculate d, the mod inverse of e.
- print('Calculating d that is mod inverse of e...')
- d = cryptomath.findModInverse(e, (p - 1) * (q - 1))
The third step is to find the mod inverse of e. The findModInverse() function that we wrote
for our cryptomath module in Chapter 14 will do this calculation for us. The mod inverse of e
is stored in a variable named d.
makeRsaKeys.py
- publicKey = (n, e)
- privateKey = (n, d)
In the RSA cipher, each key is made up of two numbers. The public key will be the integers
stored in n and e, and the private key will be the integers stored in n and d. Lines 36 and 37 store
these integers as tuples in the variables publicKey and privateKey.
There’s no reason e has to be in the public key and d in the private key, and you could swap
them. However, once you make the public key public, you must keep the private key a secret.
makeRsaKeys.py
- print('Public key:', publicKey)
- print('Private key:', privateKey)
- return (publicKey, privateKey)