Here is a simple Java program that takes user inputs for the message (encrypted or human readable) then either encrypt or decrypt the message based on provided key. This program is not intended to run as a real world modern encryption and encryption program, by to learn how to use while and for loops.
Warning!
Do not copy my code as per copyright and plagiarism regulations of your academic institution. This Java code is provided as it is for demonstration purposes.// Import Java libraries import java.util.Scanner; public class EncryptionCode { public static void main(String[] args) { // Create a Scanner object attached to the keyboard Scanner in = new Scanner (System.in); // Plain text message to be encrypted from user System.out.print("Please enter something to be encrypted or the encrypted message: "); String userMessage = in.nextLine(); /* Integer encryption or description key from user. * User must provide the opposite mathematical operation of the original key for description. * For example, if encryption was done using key 6, then use -6 to decrypt. */ System.out.print("Please enter an integer value between 1 and 6 for encryption key: "); int userKey = in.nextInt(); // User error check for key while (userKey > 6) { System.out.print("Your key must be between 1 and 6.\nPlease enter an integer value between 1 and 6: "); userKey = in.nextInt(); } // Modulus from user (THIS IS NOT IN USE) System.out.print("What is the secret secondary key? "); int secondKey = in.nextInt(); // Encryption or decryption processing String message = userMessage; int key = userKey; char [] chars = message.toCharArray(); for(char i : chars) { i += key; System.out.print(i); } } }
Explantion
Program will request the user for the message and store it in a String type variable. The user may enter either plain human readable message with letters, numbers and characters. The user may also enter an encrypted message. User can select what value should be used for the encryption key. However, because the program is using the Ascii Table, the program will only works if the input is between 1 and 6 (inclusive). Using a while loop, the program will check if the user has entered an acceptable integer value for the key.
For decryption, the user must know the original encryption key. The decryption process is opposite of encryption process in terms of methamatics. This program simple add a value on the Ascii table to encrypt each letter. This is what is done in the last for loop.
Note this program also contain a secret secondary key, which currently not in use. I added that to show that you can modify the program to include multiple encryption keys and do something with keys to create bit more complex calculations.