Encryption and Decryption of String according to given technique | Python3 implementation for Custom Encryption and Decryption of String ; Function to encrypt the ; Matrix to generate the Encrypted String ; Fill the matrix row - wise ; Loop to generate encrypted ; Function to decrypt the ; Matrix to generate the Encrypted String ; Fill the matrix column - wise ; Loop to generate decrypted ; Driver Code ; Encryption of String ; Decryption of String
from math import ceil , floor , sqrt NEW_LINE def encryption ( s ) : NEW_LINE INDENT l = len ( s ) NEW_LINE b = ceil ( sqrt ( l ) ) NEW_LINE a = floor ( sqrt ( l ) ) NEW_LINE encrypted = " " NEW_LINE if ( b * a < l ) : NEW_LINE INDENT if ( min ( b , a ) == b ) : NEW_LINE INDENT b = b + 1 NEW_LINE DEDENT else : NEW_LINE INDENT a = a + 1 NEW_LINE DEDENT DEDENT arr = [ [ ' ▁ ' for i in range ( a ) ] for j in range ( b ) ] NEW_LINE k = 0 NEW_LINE for j in range ( a ) : NEW_LINE INDENT for i in range ( b ) : NEW_LINE INDENT if ( k < l ) : NEW_LINE INDENT arr [ j ] [ i ] = s [ k ] NEW_LINE DEDENT k += 1 NEW_LINE DEDENT DEDENT for j in range ( b ) : NEW_LINE INDENT for i in range ( a ) : NEW_LINE INDENT encrypted = encrypted + arr [ i ] [ j ] NEW_LINE DEDENT DEDENT return encrypted NEW_LINE DEDENT def decryption ( s ) : NEW_LINE INDENT l = len ( s ) NEW_LINE b = ceil ( sqrt ( l ) ) NEW_LINE a = floor ( sqrt ( l ) ) NEW_LINE decrypted = " " NEW_LINE arr = [ [ ' ▁ ' for i in range ( a ) ] for j in range ( b ) ] NEW_LINE k = 0 NEW_LINE for j in range ( b ) : NEW_LINE INDENT for i in range ( a ) : NEW_LINE INDENT if ( k < l ) : NEW_LINE INDENT arr [ j ] [ i ] = s [ k ] NEW_LINE DEDENT k += 1 NEW_LINE DEDENT DEDENT for j in range ( a ) : NEW_LINE INDENT for i in range ( b ) : NEW_LINE INDENT decrypted = decrypted + arr [ i ] [ j ] NEW_LINE DEDENT DEDENT return decrypted NEW_LINE DEDENT s = " Geeks ▁ For ▁ Geeks " NEW_LINE encrypted = " " NEW_LINE decrypted = " " NEW_LINE encrypted = encryption ( s ) NEW_LINE print ( encrypted ) NEW_LINE decrypted = decryption ( encrypted ) NEW_LINE print ( decrypted ) NEW_LINE