Keyword Cipher | Java program for encoding the string using classical cipher ; Function generates the encoded text ; This array represents the 26 letters of alphabets ; This loop inserts the keyword at the start of the encoded string ; To check whether the character is inserted earlier in the encoded string or not ; This loop inserts the remaining characters in the encoded string . ; Function that generates encodes ( cipher ) the message ; This loop ciphered the message . Spaces , special characters and numbers remain same . ; Driver code ; Hold the Keyword ; Function call to generate encoded text ; Message that need to encode ; Function call to print ciphered text
class GFG { static String encoder ( char [ ] key ) { String encoded = " " ; boolean [ ] arr = new boolean [ 26 ] ; for ( int i = 0 ; i < key . length ; i ++ ) { if ( key [ i ] >= ' A ' && key [ i ] <= ' Z ' ) { if ( arr [ key [ i ] - 65 ] == false ) { encoded += ( char ) key [ i ] ; arr [ key [ i ] - 65 ] = true ; } } else if ( key [ i ] >= ' a ' && key [ i ] <= ' z ' ) { if ( arr [ key [ i ] - 97 ] == false ) { encoded += ( char ) ( key [ i ] - 32 ) ; arr [ key [ i ] - 97 ] = true ; } } } for ( int i = 0 ; i < 26 ; i ++ ) { if ( arr [ i ] == false ) { arr [ i ] = true ; encoded += ( char ) ( i + 65 ) ; } } return encoded ; } static String cipheredIt ( String msg , String encoded ) { String cipher = " " ; for ( int i = 0 ; i < msg . length ( ) ; i ++ ) { if ( msg . charAt ( i ) >= ' a ' && msg . charAt ( i ) <= ' z ' ) { int pos = msg . charAt ( i ) - 97 ; cipher += encoded . charAt ( pos ) ; } else if ( msg . charAt ( i ) >= ' A ' && msg . charAt ( i ) <= ' Z ' ) { int pos = msg . charAt ( i ) - 65 ; cipher += encoded . charAt ( pos ) ; } else { cipher += msg . charAt ( i ) ; } } return cipher ; } public static void main ( String [ ] args ) { String key ; key = " Computer " ; System . out . println ( " Keyword ▁ : ▁ " + key ) ; String encoded = encoder ( key . toCharArray ( ) ) ; String message = " GeeksforGeeks " ; System . out . println ( " Message ▁ before ▁ Ciphering ▁ : ▁ " + message ) ; System . out . println ( " Ciphered ▁ Text ▁ : ▁ " + cipheredIt ( message , encoded ) ) ; } }