# Cracking Codes Practice Problem Answers

Chapter 1

1. Encrypt the following sentences with the given keys:

With key 4: "AMBIDEXTROUS: Able to pick with equal skill a right-hand pocket or a left."

With key 17: "GUILLOTINE: A machine which makes a Frenchman shrug his shoulders with good reason."

With key 21: "IMPIETY: Your irreverence toward my deity."

2. Decrypt the following ciphertexts with the given keys:

With key 15: "ZXAI: P RDHIJBT HDBTIXBTH LDGC QN HRDIRWBTC XC PBTGXRP PCS PBTGXRPCH XC HRDIAPCS."

ANSWER: KILT: A costume sometimes worn by Scotchmen in America and Americans in Scotland.

With key 4: "MQTSWXSV: E VMZEP EWTMVERX XS TYFPMG LSRSVW."

ANSWER: IMPOSTOR: A rival aspirant to public honors.

3. Encrypt the following sentence with the key 0:

"This is a silly example."

ANSWER: This is a silly example.

4. Here are some words and their encryptions. Which key was used for each word?

ROSEBUD – LIMYVOX

YAMAMOTO – PRDRDFKF

ASTRONOMY – HZAYVUVTF

5. What does this sentence encrypted with key 8 decrypt to with key 9? "UMMSVMAA: Cvkwuuwv xibqmvkm qv xtivvqvo i zmdmvom bpib qa ewzbp epqtm."

ANSWER: LDDJMDRR: TMBNLLNM OZSHDMBD HM OKZMMHMF Z QDUDMFD SGZS HR VNQSG VGHKD. (Decrypting with the incorrect key results in nonsense text.)

Chapter 2

1. Which is the operator for division, / or \ ?

ANSWER: / (The backslash \ is used for escape characters in strings, described in Chapter 3.)

2. Which of the following is an integer value, and which is a floating-point value?
• `42`
• `3.141592`

ANSWER: `42` is an integer value, `3.141592` is a floating-point value.

3. Which of the following lines are not expressions?
• `4 x 10 + 2 `
• `3 * 7 + 1 `
• `2 + `
• `42 `
• `2 + 2 `
• `spam = 42 `

ANSWER: 4 x 10 + 2 (x is not the multiplication operator, * is), 2 + (this expression is incomplete), and spam = 42 (this is an assignment statement, not an expression)

4. If you enter the following lines of code into the interactive shell, what do lines (1) and (2) print?

spam = 20
spam + 20 # (1)
SPAM = 30
spam # (2)

ANSWER: Line 1 prints `40`, line 2 prints `20`. (`spam` and `SPAM` are two different variables.)

Chapter 3

1. If you assign spam = 'Cats' , what do the following lines print?

`spam + spam + spam`

ANSWER: `'CatsCatsCats'`

`spam * 3`

2. What do the following lines print?

`print("Dear Alice,\nHow are you?\nSincerely,\nBob")`

`print('Hello' + 'Hello')`

3. If you assign `spam = 'Four score and seven years is eighty seven years.'`, what would each of the following lines print?

`print(spam)`

`print(spam[-3])`

`print(spam[0:4] + spam)`

`print(spam[-3:-1])`

`print(spam[:10])`

`print(spam[-5:])`

`print(spam[:])`

ANSWER: Four score and seven years is eighty seven years.

4. Which window displays the >>> prompt, the interactive shell or the file editor?

5. What does the following line print?

`#print('Hello, world!')`

Chapter 4

1. What does the following piece of code print to the screen?

print(len('Hello') + len('Hello'))

ANSWER: `10` (Both calls to `len()` return integer values, and the `5`s add to the integer value `10`, which is printed on the screen.)

2. What does this code print?

i = 0
while i < 3:
print('Hello')
i = i + 1

Hello
Hello

i = 0
spam = 'Hello'
while i < 5:
spam = spam + spam[i]
i = i + 1
print(spam)

4. And this?

i = 0
while i < 4:
while i < 6:
i = i + 2
print(i)

4
6

Chapter 5

1. Using caesarCipher.py, encrypt the following sentences with the given keys:

`'"You can show black is white by argument," said Filby, "but you will never convince me."'` with key 8

`'1234567890'` with key 21

2. Using caesarCipher.py, decrypt the following ciphertexts with the given keys:

`'Kv?uqwpfu?rncwukdng?gpqwijB'` with key 2

`'XCBSw88S18A1S 2SB41SE .8zSEwAS50D5A5x81V'` with key 22

ANSWER: But all else of the world was invisible.

3. Which Python instruction would import a module named watermelon.py?

4. What do the following pieces of code display on the screen?

spam = 'foo'
for i in spam:
spam = spam + i
print(spam)

if 10 < 5:
print('Hello')
elif False:
print('Alice')
elif 5 != 5:
print('Bob')
else:
print('Goodbye')

print('f' not in 'foo')

print('foo' in 'f')

print('hello'.find('oo'))

ANSWER: -1 (The find() method returns -1 when it can't find the string.)

Chapter 6

1. Break the following ciphertext, decrypting one line at a time because each line has a different key. Remember to escape any quote characters:

qeFIP?eGSeECNNS,
5coOMXXcoPSZIWoQI,
avnl1olyD4l'ylDohww6DhzDjhuDil,
z.GM?.cEQc. 70c.7KcKMKHA9AGFK,
?MFYp2pPJJUpZSIJWpRdpMFY,
ZqH8sl5HtqHTH4s3lyvH5zH5spH4t pHzqHlH3l5K
Zfbi,!tif!xpvme!qspcbcmz!fbu!nfA

I love my kitty,
My kitty loves me,
Together we're happy as can be,

That I keep under my hat,
Of what if I shrank to the size of a rat.

Yeah, she would probably eat me.

Chapter 7

1. With paper and pencil, encrypt the following messages with the key 9 using the transposition cipher. The number of characters has been provided for your convenience.

Underneath a huge oak tree there was of swine a huge company, (61 characters)

ANSWER: Uhot on ahoamdakef pe r harhtesunnur wgyegewie,aeean t sec

That grunted as they crunched the mast: For that was ripe and fell full fast. (77 characters)

Then they trotted away for the wind grew high: One acorn they left, and no more might you spy. (94 characters)

ANSWER: T atg:renishtwhr nfogperaeeO t hynoy wnt,mt. t w eh o ttfih earyheoniayneoedrdgc d uy hol m

2. In the following program, is each spam a global or local variable?

spam = 42
def foo():
global spam
spam = 99
print(spam)

ANSWER: They are all global. (The global statement makes the spam variables in foo() global.)

3. What value does each of the following expressions evaluate to?

[0, 1, 2, 3, 4]

ANSWER: `2`

[[1, 2], [3, 4]]

ANSWER: `[1, 2]`

[[1, 2], [3, 4]]

ANSWER: `2`

['hello']

ANSWER: `'e'`

[2, 4, 6, 8, 10][1:3]

ANSWER: `[4, 6]`

list('Hello world!')

ANSWER: `['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!']`

list(range(10))

ANSWER: `2`

4. What value does each of the following expressions evaluate to?
len([2, 4])

ANSWER: `2`

len([])

ANSWER: `0`

len(['', '', ''])

ANSWER: `3`

[4, 5, 6] + [1, 2, 3]

ANSWER: `[4, 5, 6, 1, 2, 3]`

3 * [1, 2, 3] + 

ANSWER: `[1, 2, 3, 1, 2, 3, 1, 2, 3, 9]`

42 in [41, 42, 42, 42]

ANSWER: `True`

5. What are the four augmented assignment operators?

ANSWER: `+=`, `-=`, `*=`, `/=`

Chapter 8

1. Using paper and pencil, decrypt the following messages with the key 9. The _ marks a single space. The total number of characters has been counted for you.

ANSWER: He picked up the acorn and buried it straight By the side of a river both deep and great.

A_b__drottthawa_nwar_eci_t_nlel_ktShw_leec,hheat_.na__e_soogmah_a__ateniAcgakh_dmnor__ (86 characters)

ANSWER: At length he came back, and with him a She And the acorn was grown to a tall oak tree.

ANSWER: But with many a hem! and a sturdy stroke, At length he brought down the poor Raven’s own oak.

2. When you enter the following code into the interactive shell, what does each line print?

>>> math.ceil(3.0)

ANSWER: `3`

>>> math.floor(3.1)

ANSWER: `3`

>>> round(3.1)

ANSWER: `3`

>>> round(3.5)

ANSWER: `4`

>>> False and False

ANSWER: `False`

>>> False or False

ANSWER: `False`

>>> not not True

ANSWER: `True`

3. Draw the complete truth tables for the and, or, and not operators.

and Operator
AandB==Evaluates to
TrueandTrue==True
TrueandFalse==False
FalseandTrue==False
FalseandFalse==False

or Operator
AandB==Evaluates to
TrueorTrue==True
TrueorFalse==True
FalseorTrue==True
FalseorFalse==False

not Operator
notA==Evaluates to
notTrue==False
notFalse==True

4. Which of the following is correct?

if __name__ == '__main__':

if __main__ == '__name__':

if _name_ == '_main_':

if _main_ == '_name_':

ANSWER: `if __name__ == '__main__':`

Chapter 9

1. If you ran the following program and it printed the number 8 , what would it print the next time you ran it?

import random
random.seed(9)
print(random.randint(1, 10))

ANSWER: `8` (Setting the seed to the same number will cause the same random numbers to be generated.)

2. What does the following program print?

spam = [1, 2, 3]
eggs = spam
ham = eggs
ham = 99
print(ham == spam)

ANSWER: `True`

3. Which module contains the deepcopy() function?

ANSWER: The `copy` module.

4. What does the following program print?

import copy
spam = [1, 2, 3]
eggs = copy.deepcopy(spam)
ham = copy.deepcopy(eggs)
ham = 99
print(ham == spam)

ANSWER: `False`

Chapter 10

1. Which is correct: `os.exists()` or `os.path.exists()`?

ANSWER: `os.path.exists()`

2. When is the Unix Epoch?

ANSWER: January 1st, 1970 at midnight, GMT

3. What do the following expressions evaluate to?

'Foobar'.startswith('Foo')

ANSWER: `True`

'Foo'.startswith('Foobar')

ANSWER: `False`

'Foobar'.startswith('foo')

ANSWER: `False`

'bar'.endswith('Foobar')

ANSWER: `False`

'Foobar'.endswith('bar')

ANSWER: `True`

'The quick brown fox jumped over the yellow lazy dog.'.title()

ANSWER: `'The Quick Brown Fox Jumped Over The Yellow Lazy Dog.'`

Chapter 11

1. What does the following code print?

spam = {'name': 'Al'}
print(spam['name'])

ANSWER: `'Al'`

2. What does this code print?

spam = {'eggs': 'bacon'}
print('bacon' in spam)

ANSWER: `False`

3. What `for` loop code would print the values in the following spam dictionary?

`spam = {'name': 'Zophie', 'species':'cat', 'age':8}`

ANSWER: `spam = {'name': 'Zophie', 'species':'cat', 'age':8}for key in spam:    print(spam[val])`

4. What does the following line print?

print('Hello, world!'.split())

`['Hello,', 'world!']`

5. What will the following code print?

```def spam(eggs=42):     print(eggs) spam() spam('Hello')```

ANSWER: `42Hello`

6. What percentage of words in this sentence are valid English words?
"Whether it's flobulllar in the mind to quarfalog the slings and arrows of outrageous guuuuuuuuur."

ANSWER: 80% (12 out of 15 words is 12 / 15 == 0.8, or 80%)

Chapter 12

1. What does this expression evaluate to?

' Hello world'.strip()

ANSWER: `'Hello world'`

2. Which characters are whitespace characters?

3. Why does `'Hello world'.strip('o')` evaluate to a string that still has Os in it?

ANSWER: Because `strip()` will only remove `'o'` from the left or right side of the string.

4. Why does `'xxxHelloxxx'.strip('X')` evaluate to a string that still has Xs in it?

ANSWER: Because `strip('X')` will only remove `'X'`, not `'x'`.

Chapter 13

1. What do the following expressions evaluate to?
17 % 1000

ANSWER: `17`

5 % 5

ANSWER: `0`

2. What is the GCD of 10 and 15?

ANSWER: 5 (Because 5 is the largest number that evenly divides both 10 and 15.)

3. What does `spam` contain after executing `spam, eggs = 'hello', 'world'`?

ANSWER: `'hello'`

4. The GCD of 17 and 31 is 1. Are 17 and 31 relatively prime?

ANSWER: Yes. (The definition of relatively prime is having a GCD of 1.)

5. Why aren’t 6 and 8 relatively prime?

ANSWER: Because their GCD is 2, not 1.

6. What is the formula for the modular inverse of A mod C?

ANSWER: The modular inverse i is where (A * i) % C == 1

Chapter 14

1. The affine cipher is the combination of which two other ciphers?

ANSWER: The multiplicative and shift (or Caesar) cipher.

2. What is a tuple? How is a tuple different from a list?

ANSWER: A tuple is a data type that can contain multiple values like a list. Unlike a list, it's values are immutable and cannot be changed.

3. If Key A is 1, why does it make the affine cipher weak?

ANSWER: Because multiplying any number by 1 results in that number, and this means the affine cipher encrypts a letter to that same letter.

4. If Key B is 0, why does it make the affine cipher weak?

ANSWER: Because adding 0 to a number results in that number, and this means the affine cipher encrypts a letter to that same letter.

Chapter 15

1. What does `2 ** 5` evaluate to?

ANSWER: `32`

2. What does `6 ** 2` evaluate to?

ANSWER: `36`

3. What does the following code print?

for i in range(5):
if i == 2:
continue
print(i)

1
3
4

4. Does the main() function of affineHacker.py get called if another program runs import affineHacker?

ANSWER: No. (This is because when a program is imported, the `__name__` variable is set to `'affineHacker'` so `main()` isn't called.)

Chapter 16

1. Why can’t a brute-force attack be used against a simple substitution cipher, even with a powerful supercomputer?

ANSWER: There are too many possible keys, even for the most powerful computer.

2. What does the spam variable contain after running this code?

spam = [4, 6, 2, 8]
spam.sort()

ANSWER: `[2, 4, 6, 8]`

3. What is a wrapper function?

ANSWER: A wrapper function calls another function, passing its arguments to the function and returning what the function returns.

4. What does 'hello'.islower() evaluate to?

ANSWER: `True`

5. What does 'HELLO 123'.isupper() evaluate to?

ANSWER: `True`

6. What does '123'.islower() evaluate to?

ANSWER: `False` (All letters must be lowercase and the string must have at least one letter for `islower()` to return `True`

Chapter 17

1. What is the word pattern for the word hello?

ANSWER: `'0.1.2.2.3'`

2. Do mammoth and goggles have the same word pattern?

ANSWER: Yes. (`'0.1.0.0.2.3.4'`)

3. Which word could be the possible plaintext word for the cipherword PYYACAO? Alleged, efficiently, or poodle?

ANSWER: Alleged (The word pattern for both "PYYACAO" and "Alleged" is 0.1.1.2.3.2.4)

Chapter 18

1. Which cipher is the Vigenère cipher similar to, except that the Vigenère cipher uses multiple keys instead of just one key?

ANSWER: The Vigenère cipher is similar to the Caesar cipher. (If you use a key that is one character long for the Vigenère cipher, it becomes identical to the Caesar cipher.)

2. How many possible keys are there for a Vigenère key with a key length
of 10?
a. Hundreds
b. Thousands
c. Millions
d. More than a trillion

ANSWER: d. More than a trillion. (Technically, there are 141,167,095,653,376.)

3. What kind of cipher is the Vigenère cipher?

ANSWER: The Vigenère cipher is known as a polyalphabetic shift cipher because it is a shift cipher (like the Caesar cipher) that uses multiple sets of substitutions.

Chapter 19

1. What is frequency analysis?

ANSWER: Counting the frequency of letters in a ciphertext as part of cryptanalysis.

2. What are the six most commonly used letters in English?

3. What does the spam variable contain after you run the following code?

spam = [4, 6, 2, 8]
spam.sort(reverse=True)

ANSWER: `[8, 6, 4, 2]`

4. If the `spam` variable contains a dictionary, how can you get a list value of the keys in the dictionary?

ANSWER: `list(spam.keys())`

Chapter 20

1. What is a dictionary attack?

ANSWER: A dictionary attack is a brute force attack using the words in an English dictionary for the possible keys.

2. What does Kasiski examination of a ciphertext reveal?

ANSWER: Kasiski examination can reveal the length of the Vigenère key used for a ciphertext.

3. What two changes happen when converting a list value to a set value with the set() function?

ANSWER: Duplicate values are removed and the order of the values is lost (unlike lists, values in sets do not have an order)

4. If the spam variable contains `['cat', 'dog', 'mouse', 'dog']`, this list has four items in it. How many items does the list returned from list(set(spam)) have?

ANSWER: 3 (The duplicate `'dog'` value is removed.)

5. What does the following code print?

print('Hello', end='')
print('World')

Chapter 21

1. Why isn’t a one-time pad program presented in this chapter?

ANSWER: Because using the Vigenère program with a random key that is as long as the message is the same thing as a one-time pad.

2. Which cipher is the two-time pad equivalent to?

ANSWER: Re-using a one-time pad twice makes the ciphertext equivalent to being encrypted with the Vigenère cipher.

3. Would using a key twice as long as the plaintext message make the one-time pad twice as secure?

ANSWER: No. It is equally secure as a regular one-time pad since the additional letters in the key aren't used.

Chapter 22

1. How many prime numbers are there?

ANSWER: There are an infinite number of prime numbers. There is no "largest" prime number.

2. What are integers that are not prime called?

3. What are two algorithms for finding prime numbers?

ANSWER: Any two of: Trial division, Rabin-Miller, and the Sieve of Eratosthenes.

Chapter 23

1. What is the difference between a symmetric cipher and an asymmetric cipher?

ANSWER: A symmetric cipher uses the same key for encrypting and decrypting. An asymmetric cipher uses two different keys for encrypting and decrypting.

2. Alice generates a public key and a private key. Unfortunately, she later loses her private key.

a. Will other people be able to send her encrypted messages?
ANSWER: Yes. Other people will use Alice's public key to send encrypted messages to Alice.

b. Will she be able to decrypt messages previously sent to her?
ANSWER: No. Alice needs her private key to decrypt these encrypted messages.

c. Will she be able to digitally sign documents?
ANSWER: No. Alice needs her private key to digitially sign documents.

d. Will other people be able to verify her previously signed documents?
ANSWER: Yes. Other people will use Alice's public key to verify any documents she signed before she lost her private key.

3. What are authentication and confidentiality? How are they different?

ANSWER: Authentication is verifying a person's identity; that they are who they say they are. Confidentiality is keeping information secret and readable by the intended recipient.

4. What is non-repudiation?

ANSWER: Non-repudiation is the property of digital signatures that a person cannot later claim they didn't sign it.