Text Encryption and Decryption in Python
2 min readJul 15, 2023
ALGORITHM:
Encrypt Function:
- Start the
encrypt
function with the input parameterstext
andn
. - Check if the
text
is an empty string or ifn
is less than or equal to 0. If true, return the original text. - Perform the encryption process
n
times using a loop:
- Initialize two empty strings:
string
andString
. - Iterate over the characters in
text
using the range from 0 to the length oftext
: - If the index
i
is odd (not divisible by 2): - Append the character at index
i
to thestring
variable. - If the index
i
is even (divisible by 2): - Append the character at index
i
to theString
variable. - Update the
text
by concatenatingstring
andString
(resulting in the encrypted text for the current iteration).
4. Return the final encrypted text
Decrypt Function
- Start the
decrypt
function with the input parameterstext
andn
. - Check if the
text
is an empty string or ifn
is less than or equal to 0. If true, return the original text. - Perform the decryption process
n
times using a loop:
- Initialize an empty string variable called
text
to store the decrypted text for the current iteration. - Find the midpoint index (
mid
) of the inputtext
. - Split the
text
into two halves: the first half from index 0 tomid-1
and the second half from indexmid
to the end. - Iterate over the characters in the second half of the text using the range from 0 to the length of the second half:
- Append the character at index
i
from the second half to thetext
variable. - If
i
is less than the length of the first half, append the character at indexi
from the first half to thetext
variable. - Update the
text
with the decrypted text for the current iteration.
4. Return the final decrypted text
.