Hacking Secret Ciphers with Python

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

Hybrid Cryptosystems


In real life, the complicated mathematics make RSA and public-key encryption slow to compute.
This is especially true for servers that need to make hundreds or thousands of encrypted
connections a second. Instead, the RSA cipher is often used to encrypt the key for a symmetric
key cipher. The encrypted key is then sent to the other person, and that key is used to pass
messages that are encrypted using the (faster) symmetric cipher. Using a symmetric key cipher
and an asymmetric key cipher to securely communicate like this is called a hybrid
cryptosystem. More information about hybrid cryptosystems can be found at
https://en.wikipedia.org/wiki/Hybrid_cryptosystem.


It’s not recommended to use the rsaCipher.py program to encrypt the keys for, say, the
vigenereCipher.py program. We’ve already proven that the Vigenère cipher is hackable. A strong
symmetric key cipher isn’t covered in this book, but you can still use rsaCipher.py to encrypt
your files anyway.


Source Code for the RSA Cipher Program


Now that you can create key files, let’s write the program that does encryption and decryption
with the RSA cipher. Open a new file editor window by clicking on File ► New Window. Type
in the following code into the file editor, and then save it as rsaCipher.py.


Source code for rsaCipher.py




  1. RSA Cipher




  2. http://inventwithpython.com/hacking (BSD Licensed)





  3. import sys




  4. IMPORTANT: The block size MUST be less than or equal to the key size!




  5. (Note: The block size is in bytes, the key size is in bits. There




  6. are 8 bits in 1 byte.)



  7. DEFAULT_BLOCK_SIZE = 128 # 128 bytes

  8. BYTE_SIZE = 256 # One byte has 256 different values.



  9. def main():


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




  11. from a file.



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

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



  14. if mode == 'encrypt':

  15. message = '''"Journalists belong in the gutter because that is
    where the ruling classes throw their guilty secrets." -Gerald Priestland "The

Free download pdf