A quick implementation of Caesar Cipher in JavaScript using a custom defined modulo function. For more details please check: http://www.codeavenger.com/2017/05/19/JavaScript-Modulo-operation-and-the-Caesar-Cipher.html
Last active
June 15, 2021 10:07
-
-
Save mveteanu/7195798f339339e7358dca4ef911532b to your computer and use it in GitHub Desktop.
Caesar Cipher in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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