DEV Community

Cover image for Caesar’s Encryption in C++
Gokula Krishna
Gokula Krishna

Posted on Originally published at gokulakrishna.co on

Caesar’s Encryption in C++

The Caesar cipher (also known as ROT13 for a shift of 13) is one of the simplest and most widely known encryption techniques. It is a type of substitution cipher where each letter is replaced by a letter a fixed number of positions down the alphabet.

How It Works

In ROT13, each letter is shifted by 13 positions. Since the English alphabet has 26 letters, applying ROT13 twice returns the original text. This makes it both an encryption and decryption function.

Substitution table

For example, the letter A becomes N, B becomes O, and so on.

The C++ Implementation

Here is the complete C++ program for ROT13 encryption:

#include <iostream>
#include <string>
using namespace std;

string rot13(string input) {
    string output = input;
    for (int i = 0; i < output.length(); i++) {
        char c = output[i];
        if ((c >= 'a' && c <= 'z')) {
            output[i] = ((c - 'a' + 13) % 26) + 'a';
        } else if ((c >= 'A' && c <= 'Z')) {
            output[i] = ((c - 'A' + 13) % 26) + 'A';
        }
    }
    return output;
}

int main() {
    string message;
    cout << "Enter message: ";
    getline(cin, message);

    string encrypted = rot13(message);
    cout << "Encrypted: " << encrypted << endl;

    string decrypted = rot13(encrypted);
    cout << "Decrypted: " << decrypted << endl;

    system("pause");
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Testing It Out

When we encode a message:

Encoding example

And when we decode it back:

Decoding example

Since ROT13 shifts by exactly half the alphabet, the same function works for both encryption and decryption. This makes it elegantly simple, though not suitable for real security purposes.

Top comments (0)