Coders Packet

Caeser Cipher using C++

By Gokul S Nambiar

A C++ program to encrypt text using Caeser Cipher giving message and key as input and result.

The Caesar Cipher technique is a type of a substitution cipher in which each letter is replaced with a another letter depending on the key. If the key is 1 then A will turn into B and B into C and so on.

Thus to cipher a given text we need an integer value known as the key indicates the number of position each letter of the text has to be moved and each letter is moved the same number of positions. 

For example

text-ABDC

Key-1

Ciphertext-BCED

CODE

#include 
#include
using namespace std;
 
string encrypt(string plaintext, int k)
{
    string result = "";

    for (int i=0;i<plaintext.length();i++)
    {
        if (isupper(plaintext[i]))
            result += char(int(plaintext[i]+k-65)%26 +65);
    else
        result += char(int(plaintext[i]+k-97)%26 +97);
    }
    return result;
}
string decrypt(string ciphertext, int k)
{
    string result = "";

    for (int i=0;i<ciphertext.length();i++)
    {
        if (isupper(ciphertext[i]))
            result += char(int(ciphertext[i]-k-65+26)%26 +65);
    else
        result += char(int(ciphertext[i]+k-97+26)%26 +97);
    }
    return result;
}
void input(string &text,int &k)
{
    cout<<"Enter text-";
    cin>>text;
    cout<<"Enter key-";
    cin>>k;
    cout << "Text : " << text;
    cout << "\nKey: " << k;
}
int main()
{	
  int k;
  char a;
  string text;
  cout<<"Enter 'E' for encryption and 'D' for decryption-";
  cin>>a;
  input(text,k);
  if(a=='E')
    	cout << "\nCipher: " << encrypt(text, k);
    else if(a=='D')
    	cout << "\nPlaintext: " << decrypt(text, k);
    return 0;
}

Encryption

Encyption

Decryption

Decryption

Download project

Reviews Report

Submitted by Gokul S Nambiar (Gokul)

Download packets of source code on Coders Packet