Coders Packet

Vigenere Cipher using C++

By Gokul S Nambiar

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

Vigenere Cipher is a method of encryption of plain text using a single form of alphabetic substitution .The encryption process and the decryption process of the plain text is done using the Vigenere table.

The table consists of the 26 letters of the alphabet written out in different rows of a table, in which each alphabet is shifted cyclically to the left as compared to the previous row of the 26*26 sized table.

The keyword is repeated in order to increase its length and match the length of the plain text. The corresponding letter of the plaintext and the keyword is used as the row and the column and the specific letter is used as the encrypted letter.

CODE

#include<bits/stdc++.h>
using namespace std;
 
string generateKey(string pt, string key)
{
    int k = pt.size();
 
    for (int i = 0; ; i++)
    {
        if (k == i)
            i = 0;
        if (key.size() == pt.size())
            break;
        key.push_back(key[i]);
    }
    return key;
}

string encryption(string pt, string key)
{
    string cipher_text;
 
    for (int i = 0; i < pt.size(); i++)
    {
        char k = (pt[i] + key[i]) %26;
 
        k += 'A';
 
        cipher_text.push_back(k);
    }
    return cipher_text;
}

string decryption(string cipher_text, string key)
{
    string orig_text;
 
    for (int i = 0 ; i < cipher_text.size(); i++)
    {
        char k = (cipher_text[i] - key[i] + 26) %26;
 
        k += 'A';
        orig_text.push_back(k);
    }
    return orig_text;
}
 
void input(string &str,string &keyword)
{
    cout<<"Enter text-";
    cin>>str;
    cout<<"Enter keyword-";
    cin>>keyword;
    cout << "\nPlaintext : " << str;
    cout << "\nKeyword: " << keyword<<"\n";
}

int main()
{
    string str;
    string keyword;
    char a;
    cout<<"Enter E for encryption and D for decryption-";
    cin>>a;
    input(str,keyword);
    string key = generateKey(str, keyword);
    if(a=='E'){
    	string cipher_text = encryption(str, key);
    	cout << "Ciphertext : "<< cipher_text<< "\n"; 
  }
    else if(a=='D')
    cout << "Decrypted Text : "<< decryption(str, key);
    return 0;
}

ENCRYPTION

Encryption

DECRYPTION

Decryption

Download project

Reviews Report

Submitted by Gokul S Nambiar (Gokul)

Download packets of source code on Coders Packet