CaesarCipherExploration

From GIS CS4
Jump to: navigation, search

Caesar Cipher Exploration

We have been learning a number of programming techniques Khan Academy:

  • Variables
  • Text
  • Functions
  • If statements
  • For and While loops

We are now going to use these techniques to implement Caesar cipher encryption and decryption algorithms in JavaScript.

  • Login to KA
  • Create a new program (Click the New Program button)

Character Handling

Exercise 1. Letter Count?

  • Write a simple program to count the number of occurrences of alpha characters in a string variable.
 Hint: Use JavaScript function charAt()
  • Note: Alpha characters include lower and upper case letters ('a'-'z', 'A'-'Z').
  • Display the result.
  • Save program!
//////////////////////////////////////////////////////////
// Caesar Exploration program

fill(255, 0, 0);
textSize(20);

var strTest = "This is a Test!";
var iCount = 0;

for (var i = 0; i < strTest.length; i++)
{
    var ch = strTest.charAt(i);    // JavaScript string function

    // define the test for alpha character (hint: ch >= 'a' ...)
    if (/* insert test here */) 
    {
        iCount ++;    // iCount = iCount + 1;
    }
}

// output results
text("Test string: " + strTest , 50, 50);
text("Number of alpha characters: " + iCount , 50, 100);

Exercise 2. Lower or Upper?

  • Define 2 functions, IsUpper(zChar) and IsLower(zChar) to test for an upper or lower case alpha character.
  • Call these functions in your if statement to test.
  • Modify your program to count only upper case, or only lower case characters.
  • Save program!
//////////////////////////////////////////////////////////
// Character handling functions

/* Test for upper case */
var isUpper = function(zChar)
{
    return (/* define condition for upper case alpha here */);
};

Exercise 3. Convert To Upper?

  • Modify your program to convert all lower case characters in the test string to upper case.
Hint: use JavaScript function toUpperCase()
  • Replace iCount variable with strOut.
  • Display the results.
  • Save program!
//////////////////////////////////////////////////////////
// Caesar Exploration program Ex 3.

var strTest = "This is a Test!";
var strOut = "";

for (var i = 0; i < strTest.length; i++)
{
    var ch = strTest.charAt(i);    // JavaScript string function

    if (isLower(ch)) 
    {
        // convert lower to upper
        ...
    }
    strOut += ch;  // add converted character to output string
}

// output results
text("Test string: " + strTest , 50, 50);
text("Converted string: " + strOut , 50, 100);

Exercise 4. Add Encryption Function

You now have a program that indexes through the characters in a string (parses), and converts (encrypts) the lower case characters to upper case.

This is a very simple form of an encryption algorithm and will form the basis of your Caesar cipher encryption program.

First we are going to extract the main loop of your program into a function which we will call encrypt. At the moment this function simply encrypts lower case characters into upper case.

  • Define a function with a string parameter: encrypt(zStr).
  • Modify your program to move the main loop into the new function.
  • Call the function in your program.
  • Test that it still works!
  • Save program!
/* define another function */
var encrypt= function(zStr)
{
    var strCrypt = "";

    /*  main loop goes here */

    return (strCrypt);
};

var strTest = "This is a Test!"
var strCrypt = encrypt(strTest);

// display results ...

Exercise 5. Add Character Encryption Function

We are now going to define another function to perform the encryption of each character.

We will also define a key variable which will be needed to perform the Caesar shift, but we won't be using this until the next exercise.

  • Define a iKey variable in your program.
  • Add a iKey parameter to your encrypt function and pass the iKey value into the encrypt function.
  • Define another function encryptChar(zChar, ziKey).
  • Call the function for each character that you want to encrypt.
  • Test that it still works!
  • Save program!
/* Encrypt character */
var encryptChar= function(zChar, iKey)
{
    // convert the character to upper case 
    // (later we will implement the Caesar shift)
    var chCrypt = zChar.toUpperCase(0);  

    return (chCrypt );
};

var encrypt= function(zStr, iKey)
{
    ...
        ch = encryptChar(ch, ziKey);

        _strCrypt += ch;
    ...
};

var strTest = "This is a Test!"
var iKey = 7;
var strCrypt = encrypt(strTest, iKey);

// display results ...

Exercise 6. Define Caesar Encryption Function

We will now implement the Caesar shift in the EncryptChar function.

We need to convert the character to it's ASCII code in order to encrypt it.

Hint: use JavaScript function charCodeAt()
// get the code of the character at position i in the string (use i=0 for 1st or single character)
var iCode = str.charCodeAt(i); 

In Khan Academy JavaScript, there is no function for converting a code back to a character - so we will define our own:

/* define some constants */
var ASCII_UPPER_A = 65;
var ASCII_UPPER_Z = 90;
var ASCII_LOWER_a = 97;
var ASCII_LOWER_z = 122;
var NUM_LETTERS = 26;

/*
 * Convert character code to string for lower and upper case alpha.
 * numbers and non-letters are unchanged.
 * Examples:
 *   intToChar(97) = 'a'
 *   intToChar(65) = 'A'
 */
var intToChar = function(ziCharCode)
{
    var strLowerChar="abcdefghijklmnopqrstuvwxyz";
    if ((ziCharCode >= ASCII_LOWER_a) && 
        (ziCharCode <= ASCII_LOWER_z))
    {
        return strLowerChar.charAt(ziCharCode - ASCII_LOWER_a);
    }

    var strUpperChar="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    if ((ziCharCode >= ASCII_UPPER_A) && 
        (ziCharCode <= ASCII_UPPER_Z))
    {
        return strUpperChar.charAt(ziCharCode - ASCII_UPPER_A);
    }
    
    return " ";
};
  • Copy the above code into your program so that we can use it.

Now we will define our encryptChar function:

  • Note: We are assuming that only upper case alpha characters are going to passed to this function - but check anyway!
  • Use the code template below to help implement the function.
  • Test that it works!
  • Save program!
/* define another function */
var encryptChar= function(zChar, ziKey)
{
    // test for upper case character (if not upper case then return character unchanged)
    // Hint: isUpper(zChar)

    // convert char to code
    // Hint: zChar.charCodeAt(0)

    // add key value to character code
    // Hint: + ziKey

    // check that encrypted character code in in range for upper case alpha
    // Hint: use the constants that we provided above (ASCII_UPPER_A, ASCII_UPPER_Z)

    // convert code back to alpha character
    // Hint: + use the intToChar(zCode) function that we provided above

    // return the encrypted character
};

Exercise 7. Decrypt With Known Key

  • Define a function to decrypt your encrypted text using the known key.
/* Decrypt Text */
var decrypt= function(zStr, ziKey)
{
    // call Crypt function and return the decrypted string
};
  • Call the decrypt function in your program and print out the result.

Did you get your original message back?

Exercise 7. Testing, Testing 1-2-3!

Try different values of your text and key values and test that the encryption still works!

Try the following test cases:

  • Test string includes upper case characters
  • Test string includes lower case characters
  • Test string includes numeric characters
  • Test string includes non-alpha characters, e.g. punctuation characters
  • key = 0
  • 2 or 3 values where 1 <= key <= 24
  • key = 26
  • key = 98
  • key= -1
  • key = -1000

Example Code

Example Caesar Encryption Code