letters=list(string.ascii_lowercase)# Use a list of lowercase letters. https://stackoverflow.com/questions/43918437/how-to-iterate-through-the-alphabet
letterCount=0# Set variable for keeping track of which letter in the ciphertext we're on.
letterPos=0# Set variable for keeping track of the letter's position in the alphabet.
ifletter>25:# If the enciphered letter's position is not valid because it is too high, fix it by rotating around the alphabet.
letter=letter-26
ifletter<0:
letter=letter+26# If the enciphered letter's position is not valid because it is too low, fix it by rotating around the alphabet.
answer=answer+letters[letter]# Add letters together to get the enciphered text.
letterPos=letterPos+1# Iterate through letter positions in the alphabet. (neccessary to find one that matches.)
ifletterPos>25:# If the letter position is greater than 25, cycle back through the alphabet.
letterPos=letterPos-26
letterCount=letterCount+1# Keep track of how many times we're doing this.
print("\nYour enciphered text is: "+answer)
defdecrypt():
# Grab global variables.
globalciphertext
globalshiftNum
globalletters
globalletterCount
globalletterPos
globalanswer
globalcommonletter
forcinciphertext:# For every letter in the ciphertext
whileletterPos<26:# While the letter's position in the alphabet is less than 26 (and thus valid), continue.
ifnotcommonletter==0:
ifcommonletter==letters[letterPos]:# If the most frequent letter matches the current letter, set the shift to that letter because that is the shift for the cipher. Forgot the double equals for comparison.
shiftNum=letterPos-4
ifciphertext[letterCount]==letters[letterPos]:# Match the letter in the ciphertext to a letter in the alphabet and once they match, continue.
letter=int(letterPos)-int(shiftNum)# Take the position of the letter and the shift number and add them for the enciphered letter.
ifletter>25:# If the enciphered letter's position is not valid because it is too high, fix it by rotating around the alphabet.
letter=letter-26
ifletter<0:
letter=letter+26# If the enciphered letter's position is not valid because it is too low, fix it by rotating around the alphabet.
answer=answer+letters[letter]# Add letters together to get the enciphered text.
letterPos=letterPos+1# Iterate through letter positions in the alphabet. (neccessary to find one that matches.)
ifletterPos>25:# If the letter position is greater than 25, cycle back through the alphabet.
letterPos=letterPos-26
letterCount=letterCount+1# Keep track of how many times we're doing this.
commonletter=collections.Counter(ciphertext).most_common()[0][0]# Find most common letter and thus the shift https://stackoverflow.com/questions/47251934/how-to-count-the-most-frequent-letter-in-a-string
decrypt()# Decrypt using the frequency found in here.