Chapter 24 – Public Key Cryptography and the RSA Cipher 417
- 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. Did you specify the correct key file and encrypted file?' % (blockSize *
8, keySize))
The readFromFileAndDecrypt() function also has a check that the block size is equal to
or less than the key size. This should always pass, because if the block size was too small, then it
would have been impossible to create this encrypted file. Most likely the wrong private key file
was specified for the keyFilename parameter, which means the key would not have decrypted
the file correctly anyway.
rsaCipher.py
Convert the encrypted message into large int values.
- encryptedBlocks = []
- for block in encryptedMessage.split(','):
- encryptedBlocks.append(int(block))
The encryptedMessage string contains many integer characters joined together with
commas. Line 150’s for loop iterates over the list returned by the split() method. This list
contains strings of individual blocks. The integer form of these strings is appended to the
encryptedBlocks list (which starts as an empty list on line 149) each time line 151 is
executed. After the for loop on line 150 completes, the encryptedBlocks list contains
integer values of the numbers that were in the encryptedMessage string.
rsaCipher.py
Decrypt the large int values.
- return decryptMessage(encryptedBlocks, messageLength, (n, d),
blockSize)
The list in encryptedBlocks is passed to decryptMessage(), along with
messageLength, the private key (which is a tuple value of the two integers in n and d), and
the block size. The decryptMessage() function returns a single string value of the decrypted
message, which itself is returned from readFileAndDecrypt() on line 154.
rsaCipher.py
If rsaCipher.py is run (instead of imported as a module) call
the main() function.
- if name == 'main':
- main()