CaesarCipherDecryptionExampleCode

From GIS CS4
Jump to: navigation, search
//////////////////////////////////////////////////////////
// Character handling functions

/* 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;

/* Test for upper case */
var isUpper = function(zChar)
{
    return ((zChar >= 'A') && (zChar <= 'Z'));
};

/* Test for lower case */
var isLower = function(zChar)
{
    zChar.match('[^A-Z]');
    return ((zChar >= 'a') && (zChar <= 'z'));
};

/*
 * 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 " ";
};

////////////////////////////////////////////////////
// Caesar cipher functions...

/* Encrypt character */
var encryptChar= function(zChar, ziKey)
{
    // convert the character to upper case 
    var chCrypt = zChar.toUpperCase(0);  

    // only encode upper case characters
    if (isUpper(chCrypt))
    {
        // offset by key
        var iNewCode = chCrypt.charCodeAt(0) + ziKey;   
        
        /* check that character code doesn't exceed upper range */
        while (iNewCode > ASCII_UPPER_Z) 
        {
            iNewCode -= NUM_LETTERS;
        }
    
        /* check that character code doesn't exceed lower range */
        while (iNewCode < ASCII_UPPER_A) 
        {
            iNewCode += NUM_LETTERS;
        }

        return (intToChar(iNewCode));
    }
    return (zChar);  // non alpha characters unchanged
};

/* Encrypt Text */
var encrypt= function(zStr, ziKey)
{
    var strCrypt = "";

    for (var i = 0; i < zStr.length; i++)
    {
        var ch = zStr.charAt(i); 
    
        strCrypt += encryptChar(ch, ziKey);  
    }

    return (strCrypt);
};

////////////////////////////////////////////////////
// Functions to determine common word usage...

/* return number of occurences of zStr in zstrMsg */
var getWordCount = function(zstrMsg, zStr) 
{
    var iWordCount = 0;
    var iIndex = 0;
    var bKeepSearching = true;
    var strMsg = zstrMsg.toUpperCase(0);
    var strSearch = zStr.toUpperCase(0);
    
    while (bKeepSearching)
    {
        iIndex = strMsg.indexOf(strSearch, iIndex);
        if (iIndex >= 0)
        {
            iWordCount++;
            iIndex += strSearch.length;
        }
        else
        {
            bKeepSearching = false;
        }
    }
    return iWordCount;
};

/* return number of occurences of common words in zstrMsg */
var getCommonWordCount = function(zstrMsg) 
{
    var strDictionary=["THE","AND","BUT","ALSO", "WAS", "OUR", 
                    "FOR", "WITH"];
    
    /* for each word in the dictionary */
    var iWordCount = 0;

    for (var index = 0; index < strDictionary.length; index++)
    {
        iWordCount += getWordCount(zstrMsg, strDictionary[index]);
    }
    return iWordCount;
};

/* get best fit key by checking for common words
   return key value (-1 means unsuccessful).
*/
var getBestFitKey = function(zStr)
{
    // try all possible key values 
    // for best common word frequency match
    var iBestFitKey = 0;
    var iBestWordCount = 0;
    
    // try all key values 0-25 and look for best match
    for (var iKey = 0; iKey <= 25; iKey++)
    {
        var strDecryptedMsg = encrypt(zStr, iKey);
        var iWordCount = getCommonWordCount(strDecryptedMsg);
        if (iWordCount > iBestWordCount)
        {
            iBestWordCount = iWordCount;
            iBestFitKey = iKey;
        }
    }
    
    if (iBestWordCount > 0)
    {
        return iBestFitKey;
    }
    return -1;  // no match found
};

//////////////////////////////////////////////////////////
// Caesar Decryption program Ex 3.

var strEncryptedMsg = "ADRPITS XC RWXPCV BPX, IWPXAPCS, VGPRT\n" +
    " XCITGCPIXDCPA HRWDDA LPH RGTPITS ID\n" +
    " EGDKXST P WXVW FJPAXIN RWGXHIXPC\n" +
    " TSJRPIXDC UDG IWT RWXASGTC DU\n" +
    " XCITGCPIXDCPA LDGZTGH ADRPITS XC HDJIWTPHI\n" +
    " PHXP. DJG EGXBPGN VDPA PI VXH XH ID PAADL\n" +
    " IWTHT UPBXAXTH ID RDCIXCJT ID LDGZ XC IWTXG\n" +
    " UXTASH LXIWDJI WPKXCV ID RDBEGDBXHT IWT\n" +
    " TSJRPIXDC DU IWTXG RWXASGTC.";

/* display encrypted message in red */
textSize(14);
fill(255, 0, 0);    // red
text("Encrypted message:\n" + strEncryptedMsg, 20, 20);

var iKey = getBestFitKey(strEncryptedMsg);

// output results
fill(0, 0, 255);    // blue
if (iKey >= 0)
{
    var strDecryptedMsg = encrypt(strEncryptedMsg, iKey);
    var iWordCount = getCommonWordCount(strDecryptedMsg);

    text("Decrypted msg (key = " + iKey + 
            ", Word count = " + iWordCount + " ):\n" + 
            strDecryptedMsg, 20, 220);
}
else
{
    text("Failed to decrypt (no common words found in text)", 
            50, 200);
}