Hacking Secret Ciphers with Python

(Ann) #1
Chapter 18 – Hacking the Simple Substitution Cipher 263

2 5. print(message)
2 6. print()
2 7. print('Copying hacked message to clipboard:')
2 8. hackedMessage = decryptWithCipherletterMapping(message, letterMapping)
2 9. pyperclip.copy(hackedMessage)
3 0. print(hackedMessage)
3 1.
3 2.
3 3. def getBlankCipherletterMapping():
3 4. # Returns a dictionary value that is a blank cipherletter mapping.
3 5. return {'A': [], 'B': [], 'C': [], 'D': [], 'E': [], 'F': [], 'G': [],
'H': [], 'I': [], 'J': [], 'K': [], 'L': [], 'M': [], 'N': [], 'O': [], 'P':
[], 'Q': [], 'R': [], 'S': [], 'T': [], 'U': [], 'V': [], 'W': [], 'X': [],
'Y': [], 'Z': []}
36.
37.
38. def addLettersToMapping(letterMapping, cipherword, candidate):
39. # The letterMapping parameter is a "cipherletter mapping" dictionary
40. # value that the return value of this function starts as a copy of.
41. # The cipherword parameter is a string value of the ciphertext word.
42. # The candidate parameter is a possible English word that the
43. # cipherword could decrypt to.
44.
45. # This function adds the letters of the candidate as potential
46. # decryption letters for the cipherletters in the cipherletter
47. # mapping.
48.
49. letterMapping = copy.deepcopy(letterMapping)
50. for i in range(len(cipherword)):
51. if candidate[i] not in letterMapping[cipherword[i]]:
52. letterMapping[cipherword[i]].append(candidate[i])
53. return letterMapping
54.
55.
56. def intersectMappings(mapA, mapB):
57. # To intersect two maps, create a blank map, and then add only the
58. # potential decryption letters if they exist in BOTH maps.
59. intersectedMapping = getBlankCipherletterMapping()
60. for letter in LETTERS:
61.
62. # An empty list means "any letter is possible". In this case just
63. # copy the other map entirely.
64. if mapA[letter] == []:
65. intersectedMapping[letter] = copy.deepcopy(mapB[letter])
66. elif mapB[letter] == []:
67. intersectedMapping[letter] = copy.deepcopy(mapA[letter])

Free download pdf