Hacking Secret Ciphers with Python

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

The remaining lines in the generateKey() function print the keys on the screen with
print() calls on lines 39 and 40. Then line 42’s generateKey() call returns a tuple with
publicKey and privateKey.


makeRsaKeys.py


  1. def makeKeyFiles(name, keySize):


  2. Creates two files 'x_pubkey.txt' and 'x_privkey.txt' (where x is the




  3. value in name) with the the n,e and d,e integers written in them,




  4. delimited by a comma.




While the generateKey() function will generate the actual integers for the public and private
keys, we need to store these numbers in a file so that our RSA cipher program can use them later
to encrypt and decrypt. Each of the keys are made of two integers that are hundreds of digits long;
that’s too many to memorize or conveniently write down. The easiest way to store them is as text
files on your computer.


This means that you have to be sure that nobody hacks your computer and copies these key files.
It might be a good idea to store these files on a USB thumb drive instead of on your computer.
However, this is also risky. If someone borrows the thumb drive then they could copy the key
files, or if you accidentally break or lose the thumb drive then you will lose your own private key!


makeRsaKeys.py



  1. Our safety check will prevent us from overwriting our old key files:



  2. if os.path.exists('%s_pubkey.txt' % (name)) or
    os.path.exists('%s_privkey.txt' % (name)):

  3. sys.exit('WARNING: The file %s_pubkey.txt or %s_privkey.txt already
    exists! Use a different name or delete these files and re-run this program.' %
    (name, name))


To prevent us from accidentally deleting our key files by running the program again, line 51
checks to see if the public or private key files with the given name already exist. If they do, the
program will exit with a warning message.


makeRsaKeys.py


  1. publicKey, privateKey = generateKey(keySize)


After the check, line 54 has a call to generateKey() to get the public and private keys using
the multiple assignment trick. The generateKey() function returns a tuple of two tuples. The
first tuple has two integers for the public key and the second tuple has two integers for the private
key. These are stored in the variables publicKey and privateKey.

Free download pdf