414 http://inventwithpython.com/hacking
Email questions to the author: [email protected]
Using a key from a key file, encrypt the message and save it to a
file. Returns the encrypted message string.
- keySize, n, e = readKeyFile(keyFilename)
The encryptAndWriteToFile() function is passed three string arguments: a filename to
write the encrypted message in, a filename of the public key to use, and a message to be
encrypted. This function handles not just encrypting the string with the key, but also creating the
file that contains the encrypted contents. (The blockSize parameter can also be specified, but
it will be set to DEFAULT_BLOCK_SIZE by default, which is 128 .)
The first step is to read in the values for keySize, n, and e from the key file by calling
readKeyFile() on line 107.
rsaCipher.py
Check that key size is greater than block size.
- if keySize < blockSize 8: # 8 to convert bytes to bits
- sys.exit('ERROR: Block size is %s bits and key size is %s bits.
The RSA cipher requires the block size to be equal to or less than the key
size. Either increase the block size or use different keys.' % (blockSize * 8,
keySize))
In order for the mathematics of the RSA cipher to work, the key size must be equal to or greater
than the block size. The blockSize value is in bytes, while the key size that was stored in the
key file was in bits, so we multiply the integer in blockSize by 8 on line 110 so that both of
these values represent number of bits.
If keySize is less than blockSize * 8, the program exits with an error message. The user
will either have to decrease the value passed for blockSize or use a larger key.
rsaCipher.py
Encrypt the message
- encryptedBlocks = encryptMessage(message, (n, e), blockSize)
Now that we have the n and e values for the key, we call the encryptMessage() function
which returns a list of integer blocks on line 115. The encryptMessage() is expecting a two-
integer tuple for the key, which is why the n and e variables are placed inside a tuple that is then
passed as the second argument for encryptMessage().
rsaCipher.py
Convert the large int values to one string value.
- for i in range(len(encryptedBlocks)):