408 http://inventwithpython.com/hacking
Email questions to the author: [email protected]
The very large integer will eventually be stored in blockInt, which starts at 0 on line 45. (This
is much like how our previous cipher programs had a translated variable that started as a
blank string but eventually held the encrypted or decrypted message by the end of the program.)
Line 46’s for loop sets i to be the index of all the characters in message for this block. This
index should start at blockStart and go up to blockStart + blockSize (that is,
blockSize characters after blockStart) or len(messageBytes), whichever is smaller.
The min() call on line 46 will return the smaller of these two expressions.
The second argument to range() on line 46 should be the smaller of these values because each
block will always be made up of 128 (or whatever value is in blockSize) characters, except for
the last block. The last block might be exactly 128 characters, but more likely it is less than the
full 128 characters. In that case we want i to stop at len(messageBytes) because that will
be the last index in messageBytes.
rsaCipher.py
- blockInt += messageBytes[i] * (BYTE_SIZE ** (i % blockSize))
The value that is added to the block integer in blockInt is the ASCII value of the character
(which is what messageBytes[i] evaluates to) multiplied by (256 ^ index-of-character).
The variable i cannot directly be used for the index-of-character part of the equation, because it
is the index in the entire messageBytes object which has indexes from 0 up to
len(messageBytes). We only want the index relative to the current iteration’s block, which
will always be from 0 to blockSize. This table shows the difference between these indexes:
Table 24-4. The indexes of the full message on top, and indexes relative to the block on bottom.
1 st Block’s Indexes 2 nd Block’s Indexes 3 rd Block’s Indexes
0 1 2 ... 127 129 130 ... 255 257 258 ... 511
0 1 2 ... 127 0 1 ... 127 0 1 ... 127
By modding i by blockSize, we can get the position relative to the block. This is why line 47
is BYTE_SIZE (i % blockSize) instead of BYTE_SIZE i.
rsaCipher.py
- blockInts.append(blockInt)
- return blockInts
After line 46’s for loop completes, the very large integer for the block has been calculated. We
want to append this block integer to the blockInts list. The next iteration of line 43’s for
loop will calculate the block integer for the next block of the message.