Here’s the code from file frequency_analysis.py ___________Code___________ _____
ID: 3752854 • Letter: H
Question
Here’s the code from file frequency_analysis.py ___________Code___________ ___________Code___________
#!/usr/bin/python
import sys,getopt,math
# Print Banner def printBanner(): print 'Frequency analysis program v0.1a' print '' print ' o o' print ' )-(' print ' (O O)' print ' \=/' print ' .-"-.' print ' //\ /\\' print ' _// / \ \_' print ' =./ {,-.} \.=' print ' || ||' print ' || || hjw' print ' __|| ||__ `97' print ' `---" "---' ASCII art by chris.com ' print ' +---------------------------------+' print ' | Programmed by Youssif Al-Nashif |' print ' | May 10, 2017 |' print ' | CIS4367: Computer Security |' print ' | Florida Polytechnic University |' print ' +---------------------------------+ '
# Print usage def usage(): print 'usage:' print ' frequency_analysis.py -i <inputfile>' print '' sys.exit(2)
# Replace non-alphanumeric and non-space characters def stripLine(text): newText='' newTextNoSpaces='' for c in str.upper(text): if (c>='A' and c<='Z'): newText=newText+c newTextNoSpaces=newTextNoSpaces+c else: newText=newText+' '
return newText,newTextNoSpaces
# Get text from file def readFile(filename): # read original file text='' textNoSpaces='' file = open(filename) line = file.readline() while line != "": line, lineNoSpaces=stripLine(line) text=text+line textNoSpaces=textNoSpaces+lineNoSpaces line = file.readline() return text, textNoSpaces
# Get text statistics def getStatistics(textNoSpaces): repetition=[] totalNumberOfCharacters=0
for i in range(0,26): repetition.append(0)
for c in textNoSpaces: repetition[ord(c) - ord('A')] = repetition[ord(c) - ord('A')] + 1 totalNumberOfCharacters = totalNumberOfCharacters + 1
frequency = list(repetition)
for i in range(0, 26): frequency[i] = float(repetition[i]) / totalNumberOfCharacters
return totalNumberOfCharacters, repetition, frequency
# Print statistics def printStatistics(totalNumberOfCharacters,repetition,frequency): print 'Total number of characters is: ', totalNumberOfCharacters, ' ' numberOfDigits = int(math.ceil(math.log(totalNumberOfCharacters, 10)))
rformat='{:'+str(numberOfDigits+5)+'d}' rformat2='{:'+str(numberOfDigits+10)+'.'+str(numberOfDigits+1)+'f}'
for i in range (0,26): # print chr(ord('A')+i),rformat.format(repetition[i]),rformat2.format(frequency[i]) print rformat2.format(frequency[i]),chr(ord('A')+i),rformat.format(repetition[i]) print
# Print statistics 2 def printStatistics2(totalNumberOfCharacters, repetition, frequency): # print 'Total number of characters is: ', totalNumberOfCharacters, ' ' #numberOfDigits = int(math.ceil(math.log(totalNumberOfCharacters, 10))) numberOfDigits=3 # rformat = '{:' + str(numberOfDigits + 5) + 'd}' rformat = '{:' + str(numberOfDigits) + '.' + str(numberOfDigits) + 'f}'
for i in range(0, 26): sys.stdout.write(rformat.format(frequency[i])) sys.stdout.write(' & ') if (i==12): print
# Program Body def main(argv):
# print banner printBanner()
# get argument if not argv: usage() try: opts, args = getopt.getopt(argv,'i:',['inputFile=']) except getopt.GetoptError: usage()
for opt, arg in opts: if opt in ("-i", "--inputFile"): inputFile = arg
text, textNoSpaces=readFile(inputFile) totalNumberOfCharacters, repetition, frequency =getStatistics(textNoSpaces) # printStatistics2(totalNumberOfCharacters, repetition, frequency) printStatistics(totalNumberOfCharacters, repetition, frequency)
if __name__ == "__main__": main(sys.argv[1:]) #!/usr/bin/python
import sys,getopt,math
# Print Banner def printBanner(): print 'Frequency analysis program v0.1a' print '' print ' o o' print ' )-(' print ' (O O)' print ' \=/' print ' .-"-.' print ' //\ /\\' print ' _// / \ \_' print ' =./ {,-.} \.=' print ' || ||' print ' || || hjw' print ' __|| ||__ `97' print ' `---" "---' ASCII art by chris.com ' print ' +---------------------------------+' print ' | Programmed by Youssif Al-Nashif |' print ' | May 10, 2017 |' print ' | CIS4367: Computer Security |' print ' | Florida Polytechnic University |' print ' +---------------------------------+ '
# Print usage def usage(): print 'usage:' print ' frequency_analysis.py -i <inputfile>' print '' sys.exit(2)
# Replace non-alphanumeric and non-space characters def stripLine(text): newText='' newTextNoSpaces='' for c in str.upper(text): if (c>='A' and c<='Z'): newText=newText+c newTextNoSpaces=newTextNoSpaces+c else: newText=newText+' '
return newText,newTextNoSpaces
# Get text from file def readFile(filename): # read original file text='' textNoSpaces='' file = open(filename) line = file.readline() while line != "": line, lineNoSpaces=stripLine(line) text=text+line textNoSpaces=textNoSpaces+lineNoSpaces line = file.readline() return text, textNoSpaces
# Get text statistics def getStatistics(textNoSpaces): repetition=[] totalNumberOfCharacters=0
for i in range(0,26): repetition.append(0)
for c in textNoSpaces: repetition[ord(c) - ord('A')] = repetition[ord(c) - ord('A')] + 1 totalNumberOfCharacters = totalNumberOfCharacters + 1
frequency = list(repetition)
for i in range(0, 26): frequency[i] = float(repetition[i]) / totalNumberOfCharacters
return totalNumberOfCharacters, repetition, frequency
# Print statistics def printStatistics(totalNumberOfCharacters,repetition,frequency): print 'Total number of characters is: ', totalNumberOfCharacters, ' ' numberOfDigits = int(math.ceil(math.log(totalNumberOfCharacters, 10)))
rformat='{:'+str(numberOfDigits+5)+'d}' rformat2='{:'+str(numberOfDigits+10)+'.'+str(numberOfDigits+1)+'f}'
for i in range (0,26): # print chr(ord('A')+i),rformat.format(repetition[i]),rformat2.format(frequency[i]) print rformat2.format(frequency[i]),chr(ord('A')+i),rformat.format(repetition[i]) print
# Print statistics 2 def printStatistics2(totalNumberOfCharacters, repetition, frequency): # print 'Total number of characters is: ', totalNumberOfCharacters, ' ' #numberOfDigits = int(math.ceil(math.log(totalNumberOfCharacters, 10))) numberOfDigits=3 # rformat = '{:' + str(numberOfDigits + 5) + 'd}' rformat = '{:' + str(numberOfDigits) + '.' + str(numberOfDigits) + 'f}'
for i in range(0, 26): sys.stdout.write(rformat.format(frequency[i])) sys.stdout.write(' & ') if (i==12): print
# Program Body def main(argv):
# print banner printBanner()
# get argument if not argv: usage() try: opts, args = getopt.getopt(argv,'i:',['inputFile=']) except getopt.GetoptError: usage()
for opt, arg in opts: if opt in ("-i", "--inputFile"): inputFile = arg
text, textNoSpaces=readFile(inputFile) totalNumberOfCharacters, repetition, frequency =getStatistics(textNoSpaces) # printStatistics2(totalNumberOfCharacters, repetition, frequency) printStatistics(totalNumberOfCharacters, repetition, frequency)
if __name__ == "__main__": main(sys.argv[1:])
The Caeser cipher is a substitution cipher where each letter in the plaintext is replaced with a letter that is with distance n from the original letter in the alphabet. The distance n is the key for the cipher The encryption using the Caeser cipher for some letter a using a key n is expressed as: -E()-(+n) mod 26 To decrypt a Caeser cipher with a key n, for each letter y in the ciphertext find the following -Dy) ( n) mod 26 The Vigenère cipher is a modified version of the Caeser cipher by using the letters of a repeated keyword to encrypt the plain text. In this homework, you are asked to 1. modify your code from assignment 1 in order to be able to encrypt and decrypt using the Vigenère cipher 2. modify the posted python code frequency analysis.py to cryptanalysis a ciphertext gener- ated by the Vigenère cipher. Pick a long text novel, in the range 200k characters or more, from google and use it as your plaintext. Choose a 3 to 5 characters keyword, encrypt the plaintext, and perform the crypltanalysis on the ciphertext to determine the keylenght and the keyword
Explanation / Answer
MAX_KEY_SIZE = 26
def getMode():
while True:
print('Do you wish to encrypt or decrypt a message?’)
mode = input().lower()
if mode in 'encrypt e decrypt d'.split():
return mode
else:
print('Enter either "encrypt" or "e" or "decrypt" or "d".')
def getMessage():
print('Enter your message:')
return input()
def getKey():
key = 0
while True:
print('Enter the key number (1-%s)' % (MAX_KEY_SIZE))
key = int(input())
if (key >= 1 and key <= MAX_KEY_SIZE):
return key
def getTranslatedMessage(mode, message, key):
if mode[0] == 'd':
key = -key
translated = ''
for symbol in message:
if symbol.isalpha():
num = ord(symbol)
num +=key
if symbol.isupper():
if num > ord('Z'):
num -= 26
elif num < ord('A')
num += 26
elif symbol.islower():
if num > ord('z'):
num -= 26
elif num < ord('a’):
num += 26
translated += chr(num)
else:
translated += symbol
return translated
mode = getMode()
message = getMessage()
key = getKey()
print('Your translated text is:')
print(getTranslatedMessage(mode, message, key))