Code for encryption and decryption using Vigenère’s Cipher

0
173

Vigenere Cipher is a method of encrypting alphabetic text. It uses a simple form of polyalphabetic substitution. A polyalphabetic cipher is any cipher based on substitution, using multiple substitution alphabets .The encryption of the original text is done using the Vigenère square or Vigenère table.

  1.  The table consists of the alphabets written out 26 times in different rows, each alphabet shifted cyclically to the left compared to the previous alphabet, corresponding to the 26 possible Caesar Ciphers.
  2. At different points in the encryption process, the cipher uses a different alphabet from one of the rows.
  3. The alphabet used at each point depends on a repeating keyword.

Code

#include "stdc++.h"
using namespace std;
 
string generateKey(string str, string key) {
 int x = str.size();
 
 for (int i = 0;; i++) {
   if (x == i) i = 0;
   if (key.size() == str.size()) break;
   key.push_back(key[i]);
 }
 return key;
}
 
string encrypt(string str, string key) {
 string cipher;
 
 for (int i = 0; i < str.size(); i++) {
   char x = (str[i] + key[i]) % 26;
   x += 'A';
   cipher.push_back(x);
 }
 return cipher;
}
 
string decrypt(string cipher, string key) {
 string orig;
 
 for (int i = 0; i < cipher.size(); i++) {
   char x = (cipher[i] - key[i] + 26) % 26;
   x += 'A';
   orig.push_back(x);
 }
 return orig;
}
 
int main() {
 string str;
 string keyw;
 cout << "Enter the plain text:";
 cin >> str;
 cout << "Enter keyword:";
 cin >> keyw;
 
 string key = generateKey(str, keyw);
 string cipher = encrypt(str, key);
 
 cout << "The ciphertext is  : " << cipher << "\n";
 
 cout << "Plain Text : " << decrypt(cipher, key) << "\n";
 return 0;
}
Vigenère’s Cipher
Vigenère’s Cipher

LEAVE A REPLY