Hacking Secret Ciphers with Python

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

rsaCipher.py


  1. message.extend(blockMessage)


After the for loop on line 59 completes, blockMessage will be a list of single-character
strings that were computed from the current block integer. The strings in this list are appended to
the end of the message list with the extend() method.


rsaCipher.py


  1. return ''.join(message)


After the for loop on line 57 completes, the single-character strings in message are joined
together into a single string which is the complete message. This string is then returned from the
getTextFromBlocks() function.


The Mathematics of RSA Encrypting and Decrypting


With the numbers for e, d, and n from the public and private keys, the mathematics done on the
block integers to encrypt and decrypt them can be summarized as follows:


 Encrypted Block = Plaintext Block ^ e mod n
 Decrypted Block = Ciphertext Block ^ d mod n

rsaCipher.py


  1. def encryptMessage(message, key, blockSize=DEFAULT_BLOCK_SIZE):


  2. Converts the message string into a list of block integers, and then




  3. encrypts each block integer. Pass the PUBLIC key to encrypt.



  4. encryptedBlocks = []

  5. n, e = key


The encryptMessage() function is passed the plaintext string along with the two-integer
tuple of the private key. The function returns a list of integer blocks of the encrypted ciphertext.
First, the encryptedBlocks variable starts as an empty list that holds the integer blocks and
the two integers in key are assigned to variables n and e.


The pow() Function


While the operator does exponents, the pow() function handles exponents and mod. The
expression pow(a, b, c) is equivalent to (a
b) % c. However, the code inside the
pow() function knows how to intelligently handle very large integers and is much faster than
typing the expression (a ** b) % c. Try typing the following into the interactive shell:





pow(2, 8)




Free download pdf