Advertisement
obernardovieira

Vigenere Cypher (Cryptography)

Apr 9th, 2016
396
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.37 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3.  
  4. using std::string;
  5. using std::cout;
  6. using std::endl;
  7.  
  8. const string chars = "abcdefghijklmnopqrstuvwxyz !?.";
  9.  
  10. string encode(string input, const string key)
  11. {
  12.     string output;
  13.     int pos[2];
  14.     for(int c = 0; c < input.length(); c++)
  15.     {
  16.         pos[0] = chars.find( tolower(input[c]) );
  17.         pos[1] = chars.find( tolower(key[c]) );
  18.         if(pos[0] != string::npos && pos[1] != string::npos)
  19.         {
  20.             output.append( chars.substr( ((pos[0] + pos[1]) % 30), 1) );
  21.         }
  22.     }
  23.     return output;
  24. }
  25.  
  26. string decode(string input, const string key)
  27. {
  28.     string output;
  29.     int pos[2];
  30.     int p;
  31.     for(int c = 0; c < input.length(); c++)
  32.     {
  33.         pos[0] = chars.find( tolower(input[c]) );
  34.         pos[1] = chars.find( tolower(key[c]) );
  35.         if(pos[0] != string::npos && pos[1] != string::npos)
  36.         {
  37.             p = (pos[0] - pos[1]);
  38.             if(p < 0) p = 30+p;
  39.             output.append( chars.substr( p, 1) );
  40.         }
  41.     }
  42.     return output;
  43. }
  44.  
  45. int main()
  46. {
  47.     string message =    "hello world";
  48.     const string key =  "thelemonade";
  49.     string encoded;
  50.  
  51.     cout << "Original -> " << message << endl;
  52.     encoded = encode(message, key);
  53.     cout << "Encoded -> " << encoded << endl;
  54.     cout << "Decoded -> " << decode(encoded, key) << endl;
  55.  
  56.     return 1;
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement