Encryption and Decryption of String according to given technique | Java implementation for Custom Encryption and Decryption of String ; Function to encrypt the String ; Matrix to generate the Encrypted String ; Fill the matrix row - wise ; Loop to generate encrypted String ; Function to decrypt the String ; Matrix to generate the Encrypted String ; Fill the matrix column - wise ; Loop to generate decrypted String ; Driver Code ; Encryption of String ; Decryption of String
class GFG { static String encryption ( char [ ] s ) { int l = s . length ; int b = ( int ) Math . ceil ( Math . sqrt ( l ) ) ; int a = ( int ) Math . floor ( Math . sqrt ( l ) ) ; String encrypted = " " ; if ( b * a < l ) { if ( Math . min ( b , a ) == b ) { b = b + 1 ; } else { a = a + 1 ; } } char [ ] [ ] arr = new char [ a ] [ b ] ; int k = 0 ; for ( int j = 0 ; j < a ; j ++ ) { for ( int i = 0 ; i < b ; i ++ ) { if ( k < l ) { arr [ j ] [ i ] = s [ k ] ; } k ++ ; } } for ( int j = 0 ; j < b ; j ++ ) { for ( int i = 0 ; i < a ; i ++ ) { encrypted = encrypted + arr [ i ] [ j ] ; } } return encrypted ; } static String decryption ( char [ ] s ) { int l = s . length ; int b = ( int ) Math . ceil ( Math . sqrt ( l ) ) ; int a = ( int ) Math . floor ( Math . sqrt ( l ) ) ; String decrypted = " " ; char [ ] [ ] arr = new char [ a ] [ b ] ; int k = 0 ; for ( int j = 0 ; j < b ; j ++ ) { for ( int i = 0 ; i < a ; i ++ ) { if ( k < l ) { arr [ j ] [ i ] = s [ k ] ; } k ++ ; } } for ( int j = 0 ; j < a ; j ++ ) { for ( int i = 0 ; i < b ; i ++ ) { decrypted = decrypted + arr [ i ] [ j ] ; } } return decrypted ; } public static void main ( String [ ] args ) { String s = " Geeks ▁ For ▁ Geeks " ; String encrypted ; String decrypted ; encrypted = encryption ( s . toCharArray ( ) ) ; System . out . print ( encrypted + "NEW_LINE"); decrypted = decryption ( encrypted . toCharArray ( ) ) ; System . out . print ( decrypted ) ; } }