This is a C++ Program to implement Vigenere cipher. The Vigenère cipher is a method of encrypting alphabetic text by using a series of different Caesar ciphers based on the letters of a keyword. It is a simple form of polyalphabetic substitution.
Here is source code of the C++ Program to Implement the Vigenere Cypher. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
#include <iostream>
#include <string>
using namespace std;
class Vigenere
{
public:
string key;
Vigenere(string key)
{
for (int i = 0; i < key.size(); ++i)
{
if (key[i] >= 'A' && key[i] <= 'Z')
this->key += key[i];
else if (key[i] >= 'a' && key[i] <= 'z')
this->key += key[i] + 'A' - 'a';
}
}
string encrypt(string text)
{
string out;
for (int i = 0, j = 0; i < text.length(); ++i)
{
char c = text[i];
if (c >= 'a' && c <= 'z')
c += 'A' - 'a';
else if (c < 'A' || c > 'Z')
continue;
out += (c + key[j] - 2 * 'A') % 26 + 'A';
j = (j + 1) % key.length();
}
return out;
}
string decrypt(string text)
{
string out;
for (int i = 0, j = 0; i < text.length(); ++i)
{
char c = text[i];
if (c >= 'a' && c <= 'z')
c += 'A' - 'a';
else if (c < 'A' || c > 'Z')
continue;
out += (c - key[j] + 26) % 26 + 'A';
j = (j + 1) % key.length();
}
return out;
}
};
int main()
{
Vigenere cipher("VIGENERECIPHER");
string original =
"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";
string encrypted = cipher.encrypt(original);
string decrypted = cipher.decrypt(encrypted);
cout << original << endl;
cout << "Encrypted: " << encrypted << endl;
cout << "Decrypted: " << decrypted << endl;
}
Output:
$ g++ VigenereCipher.cpp $ a.out Beware the Jabberwock, my son! The jaws that bite, the claws that catch! Encrypted: WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY Decrypted: BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH ------------------ (program exited with code: 0) Press return to continue
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
advertisement
advertisement
Here’s the list of Best Books in C++ Programming, Data Structures and Algorithms.
Next Steps:
- Get Free Certificate of Merit in C++ Programming
- Participate in C++ Programming Certification Contest
- Become a Top Ranker in C++ Programming
- Take C++ Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Apply for Computer Science Internship
- Apply for C++ Internship
- Buy Computer Science Books
- Practice Programming MCQs
- Practice Computer Science MCQs