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 131

Examine the following program, which will predict the length of the key

used to encrypt the text using the Vigenère cipher:

import urllib.request, random, ssl

import operator

def getLetterFreqs(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

def getTextOnly(text):

# Strip out all non-alphabet characters

# There are a number of ways to do this but this is the simplest to

understand

modifiedText = str(text.strip())

modifiedText = modifiedText.replace(" ", "")

modifiedText = " ".join(modifiedText.split())

modifiedText = modifiedText.lower()

return modifiedText

def getEncryptedData():

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

AppliedCryptoPython/master/encryptedmoby.txt"

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

create_unverified_context())

readText = response.read()

textOnly = getTextOnly(readText)

return textOnly

def getFitnessScore(message, longerwords):

score = 0.0

for word in longerwords:

wordWeight = message.count(word)

if wordWeight>0:

score += wordWeight * 50 * len(word)

return score

def getDictionary():

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

Saved successfully!

Ooh no, something went wrong!