C++ Source code to encrypt and decrypt the Ceasar cipher


The following code accepts one line from the standard input and uses the functions encrypt and decrypt to break the Ceasar cipher when the key is known. In this example, the key was the number 12, the day of birth of Julius Ceasar.

[download id=”11738″]

#include <iostream>
#include <string> 

using namespace std;

#define OFFSET_SMALL (97)
#define OFFSET_BIG (65)
#define LATIN_CHARACTERS (26)

// Text and offset for the shift are sent into this function, which returns the text's encrypted version.
string encrypt(string text, int offset)
{
    string result = "";

    for (long unsigned int i = 0; i < text.length(); i++)
    {
        if (std::isalpha(text[i]))
        {
            if (std::islower(text[i]))
            {
                result += char (int(text[i] + offset - OFFSET_SMALL) % LATIN_CHARACTERS + OFFSET_SMALL);
            }
            else
            {
                result += char (int(text[i] + offset - OFFSET_BIG) % LATIN_CHARACTERS + OFFSET_BIG);
            }
        }

        else
        {
            result += text[i];
        }
    }

    return result;
}

// Text and offset for the shift are sent into this function, which returns the text's decrypted version.
string decrypt(string text, int offset)
{
    return encrypt(text, LATIN_CHARACTERS - offset);
}

int main() {
    string encrypted;
    getline(cin, encrypted);

    // Sample execution showing how to decrypt an already encrypted message.
    // Julius Ceasar was born on July 12, 100BC
    cout << decrypt(encrypted, 12);

    return 0;
}

[download id=”11738″]

.

Side note:

While authoring this post, we found a peculiar bug in the plugin named “SyntaxHlighlighter Evolved.”

Specifically, when we added the string char( in our C++ source code, we would get the following error back:

Updating failed. The response is not a valid JSON response.

To mitigate the problem, we added a space character between the word char and the open parenthesis as follows char (.

This post is also available in: Αγγλικα

Απάντηση

Αυτός ο ιστότοπος χρησιμοποιεί το Akismet για να μειώσει τα ανεπιθύμητα σχόλια. Μάθετε πώς υφίστανται επεξεργασία τα δεδομένα των σχολίων σας.