Skip to content

Instantly share code, notes, and snippets.

@mveteanu
Last active June 15, 2021 10:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mveteanu/7195798f339339e7358dca4ef911532b to your computer and use it in GitHub Desktop.
Save mveteanu/7195798f339339e7358dca4ef911532b to your computer and use it in GitHub Desktop.
Caesar Cipher in JavaScript
// Function will implement Caesar Cipher to
// encrypt / decrypt the msg by shifting the letters
// of the message acording to the key
function encrypt(msg, key)
{
var encMsg = "";
for(var i = 0; i < msg.length; i++)
{
var code = msg.charCodeAt(i);
// Encrypt only letters in 'A' ... 'Z' interval
if (code >= 65 && code <= 65 + 26 - 1)
{
code -= 65;
code = mod(code + key, 26);
code += 65;
}
encMsg += String.fromCharCode(code);
}
return encMsg;
}
// Modulo function: n mod p
function mod(n, p)
{
if ( n < 0 )
n = p - Math.abs(n) % p;
return n % p;
}
var msg = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.";
var ok = true;
// Encrypt with a wide range of keys
// ... then try to decrypt imediately
for(var i = 0; i < 300; i++)
{
var encMsg = encrypt(msg, i);
var decMsg = encrypt(encMsg, -1 * i);
if ( msg != decMsg )
ok = false;
console.log(i, msg, encMsg, decMsg);
}
console.log("Correct: " + ok);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment