If you have ever taken an encryption class, I am sure that you have heard of the Vernam Cipher. For fun today I decided to write a quick one in JavaScript which takes your message and the random key:


function vernam(msg, key) {
  var l = key.length;
  var fromCharCode = String.fromCharCode;
  return msg.replace(/[\s\S]/g, function(c, i) {
    return fromCharCode(key.charCodeAt(i % l) ^ c.charCodeAt(0));
  });
}

To you use this function you must supply both a message and a key. The returned string is the ciphertext that is to be sent to the desired recipient. Using this ciphertext and the same one-time key you used, the recipient will be able to decrypt the message.

It is true that the Vernam Cipher is unbreakable, but this is only due to the fact that you must supply a different random key every time you encrypt a message. Re-use of a cipher for multiple messages can lead to the messages being decrypted. If you are interested, read more about it here on Wikipedia (don’t worry, it is trustworthy šŸ˜› ).


1 Comment

JavaScript – XOR In Any Base | Chris West's Blog · August 20, 2013 at 4:44 PM

[…] ← Previous […]

Leave a Reply

Your email address will not be published. Required fields are marked *