Advertisement
Ihmemies

Encryption

Sep 8th, 2022
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.22 KB | None | 0 0
  1. #include  <iostream>
  2.  
  3. using namespace std;
  4.  
  5. int check_enc_key(string encryption_key) {
  6.     int length = encryption_key.length();
  7.     const string ABC = "abcdefghijklmnopqrstuvwxyz";
  8.  
  9.     // check length
  10.     if(encryption_key.length() != 26) {
  11.         cout << "Error! The encryption key must contain 26 characters." << endl;
  12.         return EXIT_FAILURE;
  13.     }
  14.  
  15.     // check chars, loop ABC
  16.     for(int i = 0; i < length; i++) {
  17.  
  18.         bool found = false;
  19.  
  20.         // check if ABC char i is found from enc key
  21.         for(int j = 0; j < length; j++) {
  22.             if(ABC[i] == encryption_key[j]) {
  23.                 found = true;
  24.  
  25.                 // check for uppercase while at it
  26.                 if(j >= 'A' && j <= 'Z') {
  27.                     cout << "Error! The encryption key must contain only lower case characters." << endl;
  28.                     return EXIT_FAILURE;
  29.                 }
  30.             }
  31.         }
  32.  
  33.         // all ABC letters must be found from encryption_key
  34.         if (found == false) {
  35.             cout << "Error! The encryption key must contain all alphabets a-z." << endl;
  36.             return EXIT_FAILURE;
  37.         }
  38.     }
  39.     return 0;
  40. }
  41.  
  42. int encrypt(string encryption_key, string plain_text) {
  43.     int length = plain_text.length();
  44.     string enc_text;
  45.     cout << encryption_key << endl;
  46.  
  47.     /*
  48.      * Edelleen ASCII-arvon selvittämisen jälkeen saat kirjaimen järjestysluvun aakkostossa,
  49.      * kun vähennät kirjaimen ASCII-arvosta ‘a’-kirjaimen ASCII-arvon (97). Tämä järjestysluku sopii
  50.      *  indeksiksi, kun etsit salausavaimesta salattavan tekstin kirjaimia.
  51.      */
  52.     for(int i = 0; i < length; i++) {
  53.         char encrypted_char = encryption_key[int(plain_text[i])-97];
  54.         // cout << plain_text[i] << " == " << encrypted_char << endl;
  55.         enc_text += encrypted_char;
  56.     }
  57.  
  58.     cout << "Encrypted text: " << enc_text << endl;
  59.     return 0;
  60. }
  61.  
  62. int main()
  63. {
  64.     string encryption_key, user_input;
  65.  
  66.     cout << "Enter the encryption key: ";
  67.     getline (cin, encryption_key);
  68.     check_enc_key(encryption_key);
  69.  
  70.     cout << "Enter the text to be encrypted: ";
  71.     getline (cin, user_input);
  72.  
  73.     encrypt(encryption_key, user_input);
  74.  
  75.     return 0;
  76. }
  77.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement