This article will teach you how to use Python to make custom Encryption and Decryption. To understand this program, you should know about the following Python Programming topics:
- Python if…else Statement
- Python for Loop
- Python User-defined Functions
Problem Definition
Write a program that encrypts and decrypts the user input. Note: Your input should be only lowercase characters with no spaces. Your program should have a secret distance given by the user that will be used for encryption and decryption. Each character of the user’s input should be offset by the distance value given by the user
For Encryption:
- Take the string and reverse it.
- Encrypt the reverse string with each character replaced with distance value (x) given by the user.
For Decryption:
- Take the string and reverse it.
- Decrypt the reverse string with each character replaced with distance value (x) given by the user.
Sample:
1 2 |
String input - cdu Encryption process – udc -> xgf (encrypted) |
The program should ask the user for input to encrypt and then display the resulting encrypted output. Next, your program should ask the user for input to decrypt and then display the resulting decrypted output.
1 2 3 4 5 6 7 |
Enter phrase to Encrypt (lowercase, no spaces): cdu Enter distance value: 3 Result: xgf Enter phrase to Decrypt (lowercase, no spaces): xgf Enter distance value: 3 Result: cdu |
Program Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
user_input = input("Enter phrase to Encrypt (lowercase, no spaces): ") user_distance = input("Enter distance value: ") string_of_numbers = "" for elem in user_input: if(elem.isnumeric() != True): string_of_numbers = string_of_numbers+elem reversed_string = string_of_numbers[::-1] if int(user_distance) > 26: a = int(user_distance) / 26 user_distance = int(user_distance) - (int(a) * 26) letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] encript_text = "" for l in reversed_string: position = letters.index(l) new_position = position + int(user_distance) if new_position > 25: new_position = new_position - 26 encript_text = encript_text + letters[new_position] print("Encrypt Result: ", encript_text) user_input = input("Enter phrase to Decrypt (lowercase, no spaces): ") user_distance = input("Enter distance value: ") string_of_numbers = "" for elem in user_input: if(elem.isnumeric() != True): string_of_numbers = string_of_numbers+elem reversed_string = string_of_numbers[::-1] decrypt_text = "" for l in reversed_string: position = letters.index(l) new_position = position - int(user_distance) if new_position > 25: new_position = new_position - 26 decrypt_text = decrypt_text + letters[new_position] print("Decrypt Result: ", decrypt_text) |
Leave a Comment