Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // program to implement vigenere cipher decryption
- #include <iostream>
- #include <vector>
- #include <algorithm>
- #include <fstream>
- #include <sstream>
- using namespace std;
- // method that recives string as input and returns decrypted string as output
- string decrypt(string original_msg, string key){
- // allchars is our keyspace
- string allChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
- int all_chars_length = allChars.length();
- // converting our string to uppercase
- transform(original_msg.begin(), original_msg.end(), original_msg.begin(), ::toupper);
- // removing all numbers, punctuations
- original_msg.erase(remove_if(original_msg.begin(), original_msg.end(), [](char c) { return (!isalpha(c) && c!='\n' && c!='\r'); } ), original_msg.end());
- // converting key to uppercase
- transform(key.begin(), key.end(), key.begin(), ::toupper);
- int index = 0;
- string decrypted_msg = "";
- // iterating over the original message character by chracter and encrypting it and appending it to the new string
- for(int i=0; i< original_msg.length(); i++){
- char letter = original_msg[i];
- if(isalpha(letter)) {
- int position = (allChars.find(letter) - allChars.find(key[index]) + allChars.length()) % allChars.length();
- char e_letter = allChars[position];
- decrypted_msg += e_letter;
- index++;
- // reset index if it is greater that key length
- if(index >= key.length()){
- index %= key.length();
- }
- // case when \n or \r is encountered
- }else{
- decrypted_msg += letter;
- index = 0;
- }
- }
- cout<<decrypted_msg;
- return decrypted_msg;
- }
- // method that decrypts file
- static void decrypt_file(string key){
- ifstream input_file;
- string file_name, data;
- cout<<"Enter File name : ";
- cin>>file_name;
- try {
- input_file.open(file_name);
- stringstream ss;
- ss << input_file.rdbuf();
- data = ss.str();
- cout<<"File read successufully!!"<<endl;
- } catch(exception e){
- cout<<e.what();
- }
- string decrypted_data = decrypt(data, key);
- cout<<"File data decrypted successfully!!"<<endl;
- ofstream output_file;
- try {
- output_file.open("C:\\Users\\MOHIT\\Desktop\\dss.txt");
- output_file << decrypted_data;
- output_file.close();
- cout<<"decrypted file stored on Desktop!!"<<endl;
- }catch(exception ee){
- cout<<ee.what();
- }
- }
- int main()
- {
- cout<<"Program to implement Vignere Cipher"<<endl;
- cout<<"Enter the decryption key : ";
- string key;
- cin>>key;
- decrypt_file(key);
- }
- /*
- Output for decrypting a file
- Enter File name :F:/python_3.4/sample.txt
- Enter File name : F:/python_3.4/sample.txt
- File read successufully!!
- File data decrypted successfully!!
- decrypted file stored on Desktop!!
- */
Add Comment
Please, Sign In to add comment