12. Encryption

Encode a message with an encryption cipher and then decode it. The cipher is a randomized, shuffled, alphabetic list.

Description: Encode a message with an encryption cipher and then decode it. The cipher is a randomized, shuffled, alphabetic list.

Code

package asu.encryption;
import java.util.Random;
import java.util.Scanner;
public class Encryption {

    public static void main(String[] args) {
        int n = 26;
        char[] alphabet = new char[n];
        char[] key = new char[n];
        for (int i = 0; i < n; i++) {
            alphabet[i] = (char) (i + 65);
            key[i] = alphabet[i];
        }
        key = createRandomKey(key);
        
        String input = "Experience is the teacher of all thikngs - Julius Caear";
        input = input.toUpperCase();
        
        String output = encrypt(input, key);
        System.out.println(output);
        
        Scanner scanner = new Scanner(System.in);
        System.out.println("To see the encryption key type <enter>:");
        String getEnter1 = scanner.nextLine();
        
        for(int i = 0; i < n; i++) {
            System.out.print(alphabet[i] + " ");
        }
        System.out.println("");
        for (int i = 0; i < n; i++) {
            System.out.print(key[i] + " ");
        }
        System.out.println("");
        System.out.println("To see the orginal message type <enter>:");
        String getEnter2 = scanner.nextLine();
        System.out.println(input);
    }
    
    public static char[] createRandomKey(char[] key) {
        int n = key.length;
        int m = n * n;
        Random r = new Random();
        for (int p = 0; p < m; p++) {
            int swap1 = r.nextInt(n);
            int swap2 = r.nextInt(n);
            char temp = key[swap1];
            key[swap1] = key[swap2];
            key[swap2] = temp;
        }
        return key;
    }
    public static String encrypt(String input, char[] key) {
        String output = "";
        
        for (int k = 0; k < input.length(); k++) {
            char thisChar = input.charAt(k);
            if (thisChar == ' ') {
                output += ' ';
            } else if ((int)thisChar > 91 || (int)thisChar < 65) {
                output += "*";
            } else {
                int index = (int) input.charAt(k) - 65;
                output += key[index];
            }
        }   
        return output;
    }
}

Output

AYEAJWARTA WX ZGA ZAPTGAJ SF PVV ZGWRKX * UNVWNX TPAXPJ
To see the encryption key type <enter>:

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
P I T M A F K G W U B V D R S E L J X Z N O Q Y H C
To see the original message type <enter>:

 EXPERIENCE IS THE TEACHER OF ALL THINGS - JULIUS CAESAR 

Last updated