Chapter 24 – Public Key Cryptography and the RSA Cipher 387
makeRsaKeys.py
- def main():
create a public/private keypair with 1024 bit keys
- print('Making key files...')
- makeKeyFiles('al_sweigart', 1024)
- print('Key files made.')
When makeRsaKeys.py is run, the main() function is called, which will create the key files.
Since the keys might take a while for the computer to generate, we print a message on line 9
before the makeKeyFiles() call so the user knows what the program is doing.
The makeKeyFiles() call on line 1 0 passes the string 'al_sweigart' and the integer
1024. This will generate keys with a size of 1024 bits and store them in files named
al_sweigart_pubkey.txt and al_sweigart_privkey.txt.
The Program’s generateKey() Function
makeRsaKeys.py
- def generateKey(keySize):
Creates a public/private key pair with keys that are keySize bits in
size. This function may take a while to run.
Step 1: Create two prime numbers, p and q. Calculate n = p * q.
- print('Generating p prime...')
- p = rabinMiller.generateLargePrime(keySize)
- print('Generating q prime...')
- q = rabinMiller.generateLargePrime(keySize)
- n = p * q
The first step of creating keys is coming up with two random prime numbers which are called p
and q. The generateLargePrime() function we wrote in the last chapter’s rabinMiller.py
program will return a prime number (as an integer value) of the size determined by the value in
keySize on line 19 and line 21. These integer values are stored in variables named p and q.
On line 2 2 , the number n is calculated by multiplying p and q, and stored in n.
makeRsaKeys.py
Step 2: Create a number e that is relatively prime to (p-1)*(q-1).
- print('Generating e that is relatively prime to (p-1)*(q-1)...')
- while True:
Keep trying random numbers for e until one is valid.
- e = random.randrange(2 (keySize - 1), 2 (keySize))
- if cryptomath.gcd(e, (p - 1) * (q - 1)) == 1: