m2skills

CAESAR CPP DEC

Aug 24th, 2017
1,696
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.26 KB | None | 0 0
  1. // program to implement ceasar cipher decryption
  2.  
  3. #include <iostream>
  4. #include <vector>
  5. #include <algorithm>
  6. #include <fstream>
  7. #include <sstream>
  8.  
  9. using namespace std;
  10.  
  11. string decrypt(string original_msg, int shift_value){
  12.  
  13.     string allChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
  14.     int all_chars_length = allChars.length();
  15.  
  16.  
  17.     string decrypted_msg = "";
  18.  
  19.     for(int i=0; i< original_msg.length(); i++){
  20.         char letter = original_msg[i];
  21.         int position = allChars.find(letter);
  22.         if(position >= 0) {
  23.             position -= shift_value;
  24.             if(position < 0){
  25.                 position += all_chars_length;
  26.             }
  27.             position %= all_chars_length;
  28.             char e_letter = allChars[position];
  29.             decrypted_msg += e_letter;
  30.  
  31. }else{
  32.             decrypted_msg += letter;
  33.         }
  34.     }
  35.  
  36.  
  37.     return decrypted_msg;
  38. }
  39.  
  40.  
  41. static void decrypt_file(int shift_value){
  42.     ifstream input_file;
  43.     string file_name, data;
  44.     cout<<"Enter File name : ";
  45.     cin>>file_name;
  46.     try {
  47.         input_file.open(file_name);
  48.         stringstream ss;
  49.         ss << input_file.rdbuf();
  50.         data = ss.str();
  51.         cout<<"File read successufully!!"<<endl;
  52.     } catch(exception e){
  53.         cout<<e.what();
  54.     }
  55.     string decrypted_data = decrypt(data, shift_value);
  56.     cout<<"File data decrypted successfully!!"<<endl;
  57.     ofstream output_file;
  58.     try {
  59.         output_file.open("C:\\Users\\MOHIT\\Desktop\\ss.txt");
  60.         output_file << decrypted_data;
  61.         output_file.close();
  62.         cout<<"decrypted file stored on Desktop!!"<<endl;
  63.     }catch(exception ee){
  64.         cout<<ee.what();
  65.     }
  66.  
  67.  
  68. }
  69.  
  70. int main()
  71. {
  72.     //cout << decrypt("My name is mohit, hello", 3) << endl;
  73.     cout<<"Program to implement Ceasar Cipher"<<endl;
  74.     cout<<"Enter shift value for decryption : ";
  75.     int shift_value;
  76.     cin>>shift_value;
  77.     decrypt_file(shift_value);
  78. }
  79.  
  80. /*
  81. Output for decrypting a file
  82. Program to implement Ceasar Cipher
  83. Enter shift value for decryption : 3
  84. Enter File name : F:/python_3.4/sample.txt
  85. File read successufully!!
  86. File data decrypted successfully!!
  87. decrypted file stored on Desktop!!
  88.  
  89.  
  90.  */
Add Comment
Please, Sign In to add comment