Hacking Secret Ciphers with Python

(Ann) #1
Chapter 24 – Public Key Cryptography and the RSA Cipher 387

makeRsaKeys.py


  1. def main():


  2. create a public/private keypair with 1024 bit keys



  3. print('Making key files...')

  4. makeKeyFiles('al_sweigart', 1024)

  5. 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


  1. def generateKey(keySize):


  2. Creates a public/private key pair with keys that are keySize bits in




  3. size. This function may take a while to run.






  4. Step 1: Create two prime numbers, p and q. Calculate n = p * q.



  5. print('Generating p prime...')

  6. p = rabinMiller.generateLargePrime(keySize)

  7. print('Generating q prime...')

  8. q = rabinMiller.generateLargePrime(keySize)

  9. 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



  1. Step 2: Create a number e that is relatively prime to (p-1)*(q-1).



  2. print('Generating e that is relatively prime to (p-1)*(q-1)...')

  3. while True:


  4. Keep trying random numbers for e until one is valid.



  5. e = random.randrange(2 (keySize - 1), 2 (keySize))

  6. if cryptomath.gcd(e, (p - 1) * (q - 1)) == 1:

Free download pdf