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 123

modifiedText = modifiedText.lower()

plaintext = ""

for c in modifiedText:

if (c.isalpha()):

plaintext = plaintext + c

# Determine the frequency analysis of the plaintext

frequency = {}

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

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

len(plaintext)

sum_freqs_squared = 0.0

for ltr in frequency:

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

# Results

print()

print ("The frequency should be near .065 if plaintext in English: " +

str(sum_freqs_squared))

Figure 4.7 shows the frequency analysis of the text of the Declaration of

Independence. Since the document is in English, the frequency analysis should

be near the value .065. When you are checking to see if your cryptanalysis is

complete, your result should be similar.

Figure 4.7: declaration_freq.py

Cryptanalysis with Python

Now that you understand the importance of frequency analysis (FA), you can

start to explore how to use FA to start cracking classical ciphers. The techniques

you learn here can be applied to a number of substitution-type ciphers such as

the Caesar, ROT-13, and Vigenère ciphers. As your understanding grows, you

will also be able to apply these techniques to the other classical ciphers that are

outlined in Chapter 3.

The next cryptanalysis code listing we will examine will take the Declaration

of Independence and encrypt it using a randomly generated key. It will then use

FA to examine all key possibilities; remember that when using a letter-shifting

cipher such as the Caesar cipher, there are only 26 possible keys. The code listing

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

Saved successfully!

Ooh no, something went wrong!