Write a program that computes a Caesar cipher of user input. Your program should take in a cipher key (int) and a string and output the Caesar cipher-encrypter string.

The Caesar cipher uses the English alphabet and shifts all of the characters by key letters. In this case, char types can easily be converted to int types, so Java can shift back and forth between integer addition and character conversion. For reference, you can look at any ASCII lookup table to see the conversion that Java uses between char and int.

Your program should be able to decrypt encrypted strings by entering a negative key, as below:

Make sure your program works with lowercase letters and symbols, too!

Solution

/**
 * Class: CaesarCipher
 * -----------------
 * Computes a Caesar cipher over user input.
 * Allows for encrypting AND decrypting.
 */
public class CaesarCipher extends ConsoleProgram {

	public void run() {
		println("This program uses a Caesar cipher for encryption.");
		int key = readInt("Enter encryption key: ");
		String plain = readLine("Plaintext:  ");
		String cipher = encrypt(plain, key);
		println("Ciphertext: " + cipher);
	}

	private String encrypt(String plain, int key) {
		String cipher = "";

	    // traverse text
	    for (int i = 0; i < plain.length(); i++) {
	        // apply transformation to each character
	    	Character ch = plain.charAt(i);
	    	int chInt = (int) ch;
	    	if (Character.isUpperCase(ch)) {
				 ch = (char) ('A' + (ch - 'A' + key) % 26);
	    	} else if (Character.isLowerCase(ch)){
				 ch = (char) ('a' + (ch - 'a' + key) % 26);
	    	} else {
	    		// do nothing
	    	}
	    	cipher += ch;
	    }
	    return cipher;
	}