218 http://inventwithpython.com/hacking
Email questions to the author: [email protected]
Splitting One Key into Two Keys
affineCipher.py
- def getKeyParts(key):
- keyA = key // len(SYMBOLS)
- keyB = key % len(SYMBOLS)
- return (keyA, keyB)
The affine cipher is like the Caesar cipher, except that it uses multiplication and addition (with
two integer keys, which we called Key A and Key B) instead of just addition (with one key). It’s
easier to remember just one number, so we will use a mathematical trick to convert between two
keys and one key.
The getKeyParts() function splits a single integer key into two integers for Key A and Key
B. The single key (which is in the parameter key) is divided by the size of the symbol set, and
Key A is the quotient and Key B is the remainder. The quotient part (without any remainder) can
be calculated using the // integer division operator, which is what line 25 does. The remainder
part (without the quotient) can be calculated using the % mod operator, which is what line 26
does.
It is assumed that the symbol set, as well as the size of the symbol set, is publicly known along
with the rest of the source code.
For example, with 2023 as the key parameter and a SYMBOLS string of 95 characters, Key A
would be 2023 // 95 or 21 and Key B would be 2023 % 95 or 28.
To combine Key A and Key B back into the single key, multiply Key A by the size of the symbol
set and add Key B: (21 * 95) + 28 evaluates to 2023.
The Tuple Data Type
affineCipher.py
- return (keyA, keyB)
A tuple value is similar to a list: it is a value that can store other values, which can be accessed
with indexes or slices. However, the values in a tuple cannot be modified. There is no
append() method for tuple values. A tuple is written using parentheses instead of square
brackets. The value returned on line 27 is a tuple.
For technical reasons beyond the scope of this book, the Python interpreter can execute code
faster if it uses tuples compared to code that uses lists.