A simple keyword cipher in javascript

I’m reading (slowly) the book CODES, CIPHERS, SECRETS AND CRYPTIC COMMUNICATION by Fred B. Wrixon.

The first example of a cipher is a simple letter substitution – the alphabet is basically shifted.

So I’ve written a letter substitution function that requires two letters and the phrase to be encrypted.

var keywordCipher = function(char1, char2, plaintext) {
  console.log("got ", char1, char2, plaintext);
  var comp1 = "abcdefghijklmnopqrstuvwxyz";
  var diff = comp1.indexOf(char2) - comp1.indexOf(char1);
  var msg = {
    value: plaintext,
    error: 0,
    message: "diff: " + diff
  };
  var trans = "";
  for(var i =0; i < plaintext.length; i++) {
    var plainChar = plaintext.charAt(i);
    if(plainChar == " ") {
      trans = trans.concat(" ");
    } else {
      var transCharPos = (comp1.indexOf(plainChar) + diff)%comp1.length;
      var transChar = comp1.charAt(transCharPos);
      trans = trans.concat(transChar);
    }
  }
  msg.value = trans;
  return msg;
}

You can see this in action here.


Posted: March 22nd, 2017 | Author: | Filed under: Code Reference | No Comments »