Hacking Secret Ciphers with Python

(Ann) #1
Chapter 7 – Hacking the Caesar Cipher with the Brute Force Technique 95

The argument for the print() function call is something we haven’t used before. It is a string


value that makes use of string formatting (also called string interpolation). String formatting
with the %s text is a way of placing one string inside another one. The first %s text in the string
gets replaced by the first value in the parentheses after the % at the end of the string.


Type the following into the interactive shell:





'Hello %s!' % ('world')
'Hello world!'
'Hello ' + 'world' + '!'
'Hello world!'
'The %s ate the %s that ate the %s.' % ('dog', 'cat', 'rat')
'The dog ate the cat that ate the rat.'





String formatting is often easier to type than string concatenation with the + operator, especially
for larger strings. And one benefit of string formatting is that, unlike string concatenation, you
can insert non-string values such as integers into the string. Try typing the following into the
interactive shell:





'%s had %s pies.' % ('Alice', 42)
'Alice had 42 pies.'
'Alice' + ' had ' + 42 + ' pies.'
Traceback (most recent call last):
File "", line 1, in
TypeError: Can't convert 'int' object to str implicitly





Line 34 uses string formatting to create a string that has the values in both the key and
translated variables. Because key stores an integer value, we’ll use string formatting to put
it in a string value that is passed to print().


Practice Exercises, Chapter 7, Set A


Practice exercises can be found at http://invpy.com/hackingpractice 7 A.


Summary


The critical failure of the Caesar cipher is that there aren’t that many different possible keys that
can be used to encrypt a message. Any computer can easily decrypt with all 26 possible keys, and
it only takes the cryptanalyst a few seconds to look through them to find the one that is in
English. To make our messages more secure, we will need a cipher that has more possible keys.
That transposition cipher in the next chapter can provide this for us.

Free download pdf