Program to perform a letter frequency attack on a monoalphabetic substitution cipher | Java 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
import java . util . * ; class GFG { static void printString ( String S , int N ) { String [ ] plaintext = new String [ 5 ] ; int freq [ ] = new int [ 26 ] ; int freqSorted [ ] = new int [ 26 ] ; int Used [ ] = new int [ 26 ] ; for ( int i = 0 ; i < N ; i ++ ) { if ( S . charAt ( i ) != ' ▁ ' ) { freq [ S . charAt ( i ) - ' A ' ] ++ ; } } for ( int i = 0 ; i < 26 ; i ++ ) { freqSorted [ i ] = freq [ i ] ; } String T = " ETAOINSHRDLCUMWFGYPBVKJXQZ " ; Arrays . sort ( freqSorted ) ; freqSorted = reverse ( freqSorted ) ; 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 . charAt ( i ) - ' A ' ; x = x - ch ; String curr = " " ; for ( int k = 0 ; k < N ; k ++ ) { if ( S . charAt ( k ) == ' ▁ ' ) { curr += ( char ) ' ▁ ' ; continue ; } int y = S . charAt ( k ) - ' A ' ; y += x ; if ( y < 0 ) y += 26 ; if ( y > 25 ) y -= 26 ; curr += ( char ) ( ' A ' + y ) ; } plaintext [ i ] = curr ; } for ( int i = 0 ; i < 5 ; i ++ ) { System . out . print ( plaintext [ i ] + "NEW_LINE"); } } static int [ ] reverse ( int a [ ] ) { int i , n = a . length , t ; for ( i = 0 ; i < n / 2 ; i ++ ) { t = a [ i ] ; a [ i ] = a [ n - i - 1 ] ; a [ n - i - 1 ] = t ; } return a ; } public static void main ( String [ ] args ) { String S = " B ▁ TJNQMF ▁ NFTTBHF " ; int N = S . length ( ) ; printString ( S , N ) ; } }