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.

132 Chapter 4 ■ Cryptographic Math and Frequency Analysis

commonWordsPath = "https://raw.githubusercontent.com/noidentity29/

AppliedCryptoPython/master/common_en_words.txt"

ALPHA = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

# create URL request

response = urllib.request.urlopen(commonWordsPath, context=ssl._

create_unverified_context())

readText = response.read()

# the file is in a binary format, decode

fileOfWords = readText.decode('utf-8')

# create an array for each word

words = fileOfWords.split()

# filter out the shorter words

longerwords = list(filter(lambda x: len(x)> 2, words))

return longerwords

def getKeyLength(encryptedText):

highest = 0;

highCtr = 0;

encryptedText = encryptedText.lower()

for KeyLength in range(1,26):

sampling = encryptedText[::KeyLength]

freqCheck = getFreqs(sampling)

if highest < freqCheck:

highest = freqCheck

highCtr = KeyLength

return highCtr

def getFreqs(text):

frequency = {}

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

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

sum_freqs_squared = 0.0

for ltr in frequency:

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

return sum_freqs_squared

myDictionary = getDictionary()

cipherText = getEncryptedData()

freqScore = getLetterFreqs(cipherText)

fitScore = getFitnessScore(cipherText, myDictionary)

keyLength = getKeyLength(cipherText)

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

Saved successfully!

Ooh no, something went wrong!