416 http://inventwithpython.com/hacking
Email questions to the author: [email protected]
Finally, the string in encryptedContent is returned from the
encryptAndWriteToFile() function on line 128. (This is so that the code that calls the
function can use this string to, for example, print it on the screen.)
The Full RSA Decryption Process
rsaCipher.py
- def readFromFileAndDecrypt(messageFilename, keyFilename):
Using a key from a key file, read an encrypted message from a file
and then decrypt it. Returns the decrypted message string.
- keySize, n, d = readKeyFile(keyFilename)
The readFromFileAndDecrypt() function, like encryptAndWriteToFile(), has
parameters for the encrypted message file’s filename and the key file’s filename. (Be sure to pass
the filename of the private key for keyFilename, not the public key.)
The first step is the same as encryptAndWriteToFile(): the readKeyFile() function
is called to get the values for the keySize, n, and d variables.
rsaCipher.py
Read in the message length and the encrypted message from the file.
- fo = open(messageFilename)
- content = fo.read()
- messageLength, blockSize, encryptedMessage = content.split('_')
- messageLength = int(messageLength)
- blockSize = int(blockSize)
The second step is to read in the contents of the file. The messageFilename file is opened for
reading (the lack of a second argument means open() will use “read mode”) on line 138. The
read() method call on line 139 will return a string of the full contents of the file.
Remember that the encrypted file’s format has an integer of the message length, an integer for the
block size used, and then the encrypted integer blocks (all separated by underscore characters).
Line 140 calls the split() method to return a list of these three values, and the multiple
assignment trick places the three values into the messageLength, blockSize, and
message variables respectively.
Because the values returned by split() will be strings, lines 141 and 142 will set
messageLength and blockSize to their integer form, respectively.
rsaCipher.py
Check that key size is greater than block size.