Skip to content

Instantly share code, notes, and snippets.

@wmantly
Created November 14, 2014 16:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wmantly/5521bb12da91b3e26ba7 to your computer and use it in GitHub Desktop.
Save wmantly/5521bb12da91b3e26ba7 to your computer and use it in GitHub Desktop.
Caesar's Cipher is named after Julius Caesar, who used it with a shift of three to protect messages of military significance.
A shift of three to the right would change the letter A to D, B to E, C to F, and so on.
A shift of three to the left would change the letter A to X, B to Y, C to Z, D to A, and so on.
Of course this offers no communication security whatsoever - except in Roman times when most people couldn't read to begin with.
But the Caesar Cipher is still used in cryptography, in addition to many other methods. So this is your first step into the world of security and data encryption.
To understand how to complete this challenge, you must first understand the ASCII standard. In short, every key on your keyboard has an assigned numeric value.
In Javascript, we use the following methods to get the ASCII decimal value.
'ABC'.charCodeAt(0) // >> 65
'ABC'charCodeAt(2) // >> 67
String.fromCharCode(97) // >> 'A'
Note that the fromCharCode function is called from the String prototype (note the capital S), while charCodeAt is a string instance method. Do you understand the difference? Write your explanation in comments in the .js file.
Round 1
Have the user input a message and a number to shift each letter. Print the resulting encrypted string to the #printout div.
Round 2
Make sure you ignore spaces, symbols, and numbers. The user wants to see these characters unchanged in the encrypted cipher.
Round 3
Add a decrypt method. Take an already encrypted string, and the shift number, and decrypt it back to english.
Round 4
Test your code using the given assert function.
@aonic
Copy link

aonic commented Nov 14, 2014

function shiftLetter(letter, shift) {
    var code = letter.toUpperCase().charCodeAt(0);
    var base = "A".charCodeAt(0); 
    var shift = parseInt(shift);

    // not-alphabet
    if (code > "Z".charCodeAt(0) || code < base) {
        return letter;
    }
    return String.fromCharCode((code - base + (26 + shift)) % 26 + base);
}

function encrypt(input) {
    var output = [];
    for(var i = 0; i < input.length; i++) {
        output.push(shiftLetter(input[i], 3));
    }
    return output.join('');
}

function decrypt(input) {
    var output = [];
    for(var i = 0; i < input.length; i++) {
        output.push(shiftLetter(input[i], -3));
    }
    return output.join('');
}

encrypt("hello"); //"KHOOR"
decrypt("khoor"); //"HELLO"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment