Program to perform a letter frequency attack on a monoalphabetic substitution cipher | C ++ program for the above approach ; 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 ; Driver Code ; Given string ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printString ( string S , int N ) { string plaintext [ 5 ] ; int freq [ 26 ] = { 0 } ; int freqSorted [ 26 ] ; int Used [ 26 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { if ( S [ i ] != ' ▁ ' ) { freq [ S [ i ] - ' A ' ] ++ ; } } for ( int i = 0 ; i < 26 ; i ++ ) { freqSorted [ i ] = freq [ i ] ; } string T = " ETAOINSHRDLCUMWFGYPBVKJXQZ " ; sort ( freqSorted , freqSorted + 26 , greater < int > ( ) ) ; for ( int i = 0 ; i < 5 ; i ++ ) { int ch = -1 ; for ( int j = 0 ; j < 26 ; j ++ ) { if ( freqSorted [ i ] == freq [ j ] && Used [ j ] == 0 ) { Used [ j ] = 1 ; ch = j ; break ; } } if ( ch == -1 ) break ; int x = T [ i ] - ' A ' ; x = x - ch ; string curr = " " ; for ( int k = 0 ; k < N ; k ++ ) { if ( S [ k ] == ' ▁ ' ) { curr += ' ▁ ' ; continue ; } int y = S [ k ] - ' A ' ; y += x ; if ( y < 0 ) y += 26 ; if ( y > 25 ) y -= 26 ; curr += ' A ' + y ; } plaintext [ i ] = curr ; } for ( int i = 0 ; i < 5 ; i ++ ) { cout << plaintext [ i ] << endl ; } } int main ( ) { string S = " B ▁ TJNQMF ▁ NFTTBHF " ; int N = S . length ( ) ; printString ( S , N ) ; return 0 ; }