Computer Science 161.01

A Substitution Cipher in JavaScript

Fall 2018

 

The idea:  The plain text (in this case, a word) is enciphered using a cipher alphabet that is simply the usual alphabet shuffled.  This shuffled (or “permuted”) alphabet is the secret key to both enciphering and deciphering text.  Without knowledge of the key, deciphering is difficult.  Certainly, a “brute force” attack is out of the question, as the number of keys is 25 X 24 X 23 X … X 1 (an outrageously large number!).  However, if the text is large enough, knowledge about frequencies of letters in English text can be used to eventually uncover the plain text. 

 

The “cryptograms” that occur in newspapers and puzzle books are typically based on a substitution cipher.  Deciphering is made possible by the fact that word lengths are maintained as are special punctuation symbols such as the apostrophe.  Click here for my substitution cipher web site.

 

A substitution cipher program in JavaScript:  In this program, the usual alphabet and cipher alphabet are introduced as strings alphabet and permuted.  The user then enters a word, which is immediately converted to all upper case (why?).  The program then sequences through the word, taking each character in word, and finding the appropriate substitution in permuted.  Note how alphabet and permuted are aligned.  Each newly found symbol in permuted is appended onto result.

 

Copy and paste this into the scratchpad site and have fun with it!  Note however that the program, in this simple form, naively expects that all characters in word are letters.

(How might you handle non-letters?).

 

alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

permuted = "KDPQOHEAWXNJZVURSLMGYTFBCI";

 

word = prompt("Enter a word to encrypt:");

word = word.toUpperCase();

 

i=0;

result = "";

 

while (i < word.length) {

   ind = alphabet.indexOf(word.charAt(i));

   result = result + permuted.charAt(ind);

   i++;

}

 

result

 

Note also that the program can be made very easily into a Caesar cipher program with some fixed shift, for example, 3.  What one line would you change and how?