07.07.2023 Views

Implementing-cryptography-using-python

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 4 ■ Cryptographic Math and Frequency Analysis 125

frequency = {}

for ascii in range(ord('a'), ord('a')+26):

frequency[chr(ascii)] = float(encrypted.count(chr(ascii)))/len(plaintext)

sum_freqs_squared = 0.0

for ltr in frequency:

sum_freqs_squared += frequency[ltr]*frequency[ltr]

print ("Will be near .065 despite Caesar: " + str(sum_freqs_squared))

for possible_key in range(1, 26):

sum_f_sqr = 0.0

for ltr in normal_freqs:

caesar_guess = shiftBy(ltr, possible_key)

sum_f_sqr += normal_freqs[ltr]*frequency[caesar_guess]

if abs(sum_f_sqr - .065) < .005:

print ("Key is probably: ", possible_key, " f_sqr is ",sum_f_sqr)

Figure 4.8 shows the key that was randomly generated to encrypt the text.

The code will then return the FA of the encrypted code, which will be relatively

close to .065 since it is a substitution cipher. The code looks for which key gets

the closest to .065 and will then recommend that result as a key. Each time you

execute your solution, you will generate a new key.

Figure 4.8: Cearsar_FA.py

Using an Online Word List

One useful technique to help identify when you have successfully decrypted a

historical cipher is to use known word lists. In the following example, we simply

load a text file containing 10,000 common English words. In the technique shown

we will read in the words using the .split() method to break them into a list

of words. Additionally, you will see that we are interested only in the words

that are at least three letters long. The quickest way to filter these words is to

use a filter with the lambda function. Lambda functions are functions that do not

require a name like the defined functions do. The lambda function returns a

function object that can be assigned to a variable. In Python, the most common

use for lambda functions is for a simple one-line function. You will typically

see the lambda functions used in conjunction with a map or filter function.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!