Hacking Secret Ciphers with Python

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

rsaCipher.py


  1. def main():


  2. Runs a test that encrypts a message to a file or decrypts a message




  3. from a file.



  4. filename = 'encrypted_file.txt' # the file to write to/read from

  5. mode = 'encrypt' # set to 'encrypt' or 'decrypt'


If mode is set to 'encrypt' the program encrypts a message (and writes it to the file that is
named in filename). If mode is set to 'decrypt' the program reads the contents of an
encrypted file (specified by the string in filename) to decrypt it.


rsaCipher.py


  1. if mode == 'encrypt':

  2. message = '''"Journalists belong in the gutter because that is
    where the ruling classes throw their guilty secrets." -Gerald Priestland "The
    Founding Fathers gave the free press the protection it must have to bare the
    secrets of government and inform the people." -Hugo Black'''

  3. pubKeyFilename = 'al_sweigart_pubkey.txt'
    2 1. print('Encrypting and writing to %s...' % (filename))

  4. encryptedText = encryptAndWriteToFile(filename, pubKeyFilename,
    message)



  5. print('Encrypted text:')

  6. print(encryptedText)


The message variable contains the text to be encrypted, and pubKeyFilename contains the
filename of the public key file. Line 22 calls the encryptAndWriteToFile() function,
which will encrypt message using the key, and write the encrypted message to the file named in
filename.


rsaCipher.py


  1. elif mode == 'decrypt':

  2. privKeyFilename = 'al_sweigart_privkey.txt'

  3. print('Reading from %s and decrypting...' % (filename))

  4. decryptedText = readFromFileAndDecrypt(filename, privKeyFilename)



  5. print('Decrypted text:')

  6. print(decryptedText)


The code that handles calling the decryption function is similar to the code on lines 18 to 33. The
filename of the private key file is set in privKeyFilename. The encrypted file’s filename is
stored in the filename variable. These two variables are passed to a call to

Free download pdf