Prev <<   >> On to the next chapter: Fifteen Puzzle.


Caesar Cipher

When Julius Caesar had to send military secrets to his generals, he used this cipher:

In the Caesar cipher, every letter is replaced by the letter that comes 3 slots after it in the alphabet. For example, the letter "a" is replaced by the letter "d". Letters at the end of the alphabet are wrapped around so that "z" goes to "c". Of course you can make a similar cipher by shifting by a different number of slots - the ROT13 cipher shifts by 13, and it has the property that you can decode a message by encrypting it twice.

This is another event-based program, so it is organized with the same general four phases as any event-based program. An overview:

  1. Display the visual elements on the page including two inputs (one with id "text" and the other with id "key") and an empty span of red text with id "output".
  2. Register to listen to events on the page. Here we want to listen to every single keystroke within any <input> element by registering for the keyup event.
  3. Run a function whenever an event of interest occurs. As usual, instead of giving the event handler function a name we are using an anonymous function defined inline. That function does some computation based on the "key" input and the "text" input values.
  4. Finally the function updates the page by putting the encrypted text into the <span>.

Input Validation and Input Normalization

This program does both input validation, where it rejects input that doesn't look sensible, and input normalization, where it changes the input to make it easier to work with.

Encrypting a String

Let us take a look at the encryption procedure. The general idea is to convert each letter to a number, add 3 (or whatever key), and then convert the number back to a letter again. To do this, we use two string methods:

string.indexOf(search)indexOf returns the first location of of the search string within the string.
For example, 'hello there'.indexOf('the') returns 6.
If the search string isn't found, returns -1.
string.charAt(index)charAt returns the character at the given index within the string.
For example, 'hello there'.charAt(6) returns 't'.

To encrypt the letter 'e' as 'h', we:

  1. Use alphabet.indexOf to locate 'e' in the alphabet (the answer is 4 since indexing starts at 0).
  2. If the letter is found, we add k to compute a shifted index. The remainder operator % 26 deals with the wraparound. (When k==3, we get 4+3=7.)
  3. Use alphabet.charAt to read out the letter at the shifted position. (Looking up the letter in slot 7 returns 'h'.)

Characters that are not found are passed unencrypted.

Things to Try

  1. Spaces reveal a lot about text (for example, in English, most all three-letter words turn out to be "the" or "and"). Change the program to remove spaces and other unencrypted characters.


Prev <<   >> On to the next chapter: Fifteen Puzzle.