07.07.2023 Views

Implementing-cryptography-using-python

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 4 ■ Cryptographic Math and Frequency Analysis 121

would give you enough details to attempt to break the cipher. With the Caesar

cipher, you will be able to brute-force a solution within 25 rounds. More advanced

substitution ciphers, like the Vigenère cipher, offer a little more of a challenge.

We will first take a look at understanding how frequency analysis works; we

will then apply the analysis to both the Caesar and the Vigenère cipher so that

you can truly understand the power of frequency analysis. Frequency analysis

isn’t always helpful. Take the case of the novel Gadsby. Gadsby is a 1939 novel

by Ernest Vincent Wright written as a lipogram, which does not include words

that contain the letter E. Our first example will take a small set of text and count

the occurrence of each letter, as shown here:

# initializing string

test_str = "We hold these truths to be self-evident, that all men are

created equal, "

test_str += "that they are endowed by their Creator with certain

unalienable Rights, "

test_str += "that among these are Life, "

test_str += "Liberty and the pursuit of Happiness."

# get count of each element in string

all_freq = {}

for i in test_str:

if i in all_freq:

all_freq[i] += 1

else:

all_freq[i] = 1

# printing result

print()

print ("Count of all characters in the provided text is :\n " + str(all_freq))

# frequency using collections.Counter()

from collections import Counter

# initializing string

test_str = "We hold these truths to be self-evident, that all men are created equal, "

test_str += "that they are endowed by their Creator with certain unalienable Rights, "

test_str += "that among these are Life, "

test_str += "Liberty and the pursuit of Happiness."

# using collections.Counter() to get

# count of each element in string

res = Counter(test_str)

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

Saved successfully!

Ooh no, something went wrong!