This program does a simple encryption using a Caesar cipher. It shifts each letter in the alphabet to the letter 2 positions later in the alphabet.
import objectdraw.*;
/**
* @author Barbara Lerner
* @version April 7, 2008
*
* Encrypts the word "Hello" using the Caesar Cipher. The Caesar Cipher
* shifts letters 2 positions, replacing a with c, b with d, etc.
*/
public class CaesarCipher extends WindowController {
// The highest character value
private static final char MAX_CHAR = '~';
// The lowest character value
private static final char MIN_CHAR = ' ';
// The range of characters
private static final int RANGE = MAX_CHAR - MIN_CHAR + 1;
// The number of positions the text is shifted.
private static final int KEY = 6;
// The letter substitutions
private char[] substitutions = new char[RANGE];
/**
* Display the original text and the encrypted text.
*/
public void begin () {
char c = MIN_CHAR;
for (int i = RANGE - KEY; i < RANGE; i++) {
substitutions[i] = c;
c++;
}
for (int i = 0; i < RANGE - KEY; i++) {
substitutions[i] = c;
c++;
}
for (int i = 0; i < RANGE; i++) {
System.out.print (substitutions[i]);
}
String unencryptedText = "Hello";
String encryptedText = encrypt (unencryptedText);
new Text ("Unencrypted text: " + unencryptedText, 0, 0, canvas);
new Text ("Encrypted text: " + encryptedText, 0, 20, canvas);
}
/**
* Encrypt the string using the Caesar cipher. This shifts the characters by
* 2 in the alphabet
*
* @param text the text to encrypt
* @return the encrypted text
*/
private String encrypt(String text) {
String encodedText = "";
for (int i = 0; i < text.length(); i++) {
char nextChar = text.charAt(i);
char nextEncodedChar = substitutions[nextChar - MIN_CHAR];
encodedText = encodedText + nextEncodedChar;
}
return encodedText;
}
}