Computer Science 161.01
Fall 2018
 
A Caesar Cipher Example in JavaScript
 
A Caesar cipher is one in which every letter in the plaintext message is shifted by some fixed amount.  Julius Caesar himself is known to have enciphered messages using such a cipher, with shift amount equal to 3.  The reason to “mod by 26” in the program below is so that the shifting will cause wrap-around to the beginning of the alphabet if necessary.  Thus, for example, X shifted by 3 yields A.  Interestingly, the way the program is now set up, it will encrypt something that’s not a letter to the letter C.  Can you see why?  You should be able to.
 
Try carefully tracing the program to predict the result with, say, text = "hello"
and n = 3.  Then copy and paste it into the scratchpad and mess with it some (other words, other shift amounts, etc.).  The function is a simplified version of what I actually used in developing the Caesar cipher demo site. 
 
 
  n = 3; //shift by this amount
 
  text = prompt("Enter some word");
  text = text.toUpperCase();
 
  alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  result = "";
 
  i = 0;
 
  while (i < text.length) {
     thisChar = text.charAt(i);
     index = alphabet.indexOf(thisChar);      
     result += alphabet.charAt((index + n) % 26);            
     i++;
  }
 
  result  //appears below in scratchpad
 
 
 
 
Decipher this message, knowing only that every alphabetic symbol was shifted by the same amount (not necessarily by 3, however):
               

XLMW MW XLI PEWX AIIO SJ GPEWWIW