Program to perform a letter frequency attack on a monoalphabetic substitution cipher | Function to decrypt a monoalphabetic substitution cipher using the letter frequency attack ; Stores final 5 possible deciphered plaintext ; Store the frequency of each letter in cipher text ; Stores the frequency of each letter in cipher text in descending order ; Store which alphabet is used already ; Traverse the string S ; Copy the frequency array ; Stores the string formed from concatanating the english letters in the decreasing frequency in the english language ; Sort the array in descending order ; Itearate over the range [ 0 , 5 ] ; Iterate over the range [ 0 , 26 ] ; Store the numerical equivalent of letter at ith index of array letter_frequency ; Calculate the probable shift used in monoalphabetic cipher ; Temporary string to generate one plaintext at a time ; Generate the probable ith plaintext string using the shift calculated above ; Insert whitespaces as it is ; Shift the kth letter of the cipher by x ; Add the kth calculated / shifted letter to temporary string ; Print the generated 5 possible plaintexts ; Given string ; Function Call
def printString ( S , N ) : NEW_LINE INDENT plaintext = [ None ] * 5 NEW_LINE freq = [ 0 ] * 26 NEW_LINE freqSorted = [ None ] * 26 NEW_LINE used = [ 0 ] * 26 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if S [ i ] != ' ▁ ' : NEW_LINE INDENT freq [ ord ( S [ i ] ) - 65 ] += 1 NEW_LINE DEDENT DEDENT for i in range ( 26 ) : NEW_LINE INDENT freqSorted [ i ] = freq [ i ] NEW_LINE DEDENT T = " ETAOINSHRDLCUMWFGYPBVKJXQZ " NEW_LINE freqSorted . sort ( reverse = True ) NEW_LINE for i in range ( 5 ) : NEW_LINE INDENT ch = - 1 NEW_LINE for j in range ( 26 ) : NEW_LINE INDENT if freqSorted [ i ] == freq [ j ] and used [ j ] == 0 : NEW_LINE INDENT used [ j ] = 1 NEW_LINE ch = j NEW_LINE break NEW_LINE DEDENT DEDENT if ch == - 1 : NEW_LINE INDENT break NEW_LINE DEDENT x = ord ( T [ i ] ) - 65 NEW_LINE x = x - ch NEW_LINE curr = " " NEW_LINE for k in range ( N ) : NEW_LINE INDENT if S [ k ] == ' ▁ ' : NEW_LINE INDENT curr += " ▁ " NEW_LINE continue NEW_LINE DEDENT y = ord ( S [ k ] ) - 65 NEW_LINE y += x NEW_LINE if y < 0 : NEW_LINE INDENT y += 26 NEW_LINE DEDENT if y > 25 : NEW_LINE INDENT y -= 26 NEW_LINE DEDENT curr += chr ( y + 65 ) NEW_LINE DEDENT plaintext [ i ] = curr NEW_LINE DEDENT for i in range ( 5 ) : NEW_LINE INDENT print ( plaintext [ i ] ) NEW_LINE DEDENT DEDENT S = " B ▁ TJNQMF ▁ NFTTBHF " NEW_LINE N = len ( S ) NEW_LINE printString ( S , N ) NEW_LINE