|
| 1 | +/* |
| 2 | + * Encrypts a plain text to decrypts an encrypted text back to plain using Caeser Cipher. |
| 3 | + * Example: |
| 4 | + * Enter plain text:the brown fox jumped over the lazy dog |
| 5 | + * Enter shift length:24 |
| 6 | + * Encrypted text:rfc zpmul dmv hskncb mtcp rfc jyxw bme |
| 7 | + * Decrypted text:the brown fox jumped over the lazy dog |
| 8 | + */ |
| 9 | + |
| 10 | +#include <iostream> |
| 11 | +#include <string> |
| 12 | +#include <sstream> |
| 13 | + |
| 14 | +char caeser_encrypt(char c, int shift_length); |
| 15 | +char caeser_decrypt(char c, int shift_length); |
| 16 | + |
| 17 | +int main() |
| 18 | +{ |
| 19 | + std::string plain_text, encrypted_text; |
| 20 | + int shift_length; |
| 21 | + std::cout << "Enter plain text:"; |
| 22 | + std::getline(std::cin, plain_text); |
| 23 | + std::cout << "Enter shift length:"; |
| 24 | + std::cin >> shift_length; |
| 25 | + std::stringstream ss; |
| 26 | + |
| 27 | + unsigned int text_length = plain_text.length(); |
| 28 | + |
| 29 | + // Encrypt the text |
| 30 | + // |
| 31 | + for (unsigned int i = 0; i < text_length; ++i) |
| 32 | + { |
| 33 | + ss << caeser_encrypt(plain_text[i], shift_length); |
| 34 | + } |
| 35 | + |
| 36 | + encrypted_text = ss.str(); |
| 37 | + std::cout << "Encrypted text:" << encrypted_text << std::endl; |
| 38 | + |
| 39 | + // Reset the stream |
| 40 | + // |
| 41 | + ss.str(std::string()); |
| 42 | + |
| 43 | + // Decrypt the text again |
| 44 | + // |
| 45 | + for (unsigned int i = 0; i < text_length; ++i) |
| 46 | + { |
| 47 | + ss << caeser_decrypt(encrypted_text[i], shift_length); |
| 48 | + } |
| 49 | + |
| 50 | + std::cout << "Decrypted text:" << ss.str() << std::endl; |
| 51 | + return 0; |
| 52 | +} |
| 53 | + |
| 54 | +char caeser_encrypt(char c, int shift_length) |
| 55 | +{ |
| 56 | + if (c >= 'A' && c <= 'Z') |
| 57 | + { |
| 58 | + return (((c - 'A' + shift_length) % 26) + 'A'); |
| 59 | + } |
| 60 | + else if (c >= 'a' && c <= 'z') |
| 61 | + { |
| 62 | + return (((c - 'a' + shift_length) % 26) + 'a'); |
| 63 | + } |
| 64 | + |
| 65 | + // In case of non-alpha characters, return as it is. |
| 66 | + return c; |
| 67 | +} |
| 68 | + |
| 69 | +char caeser_decrypt(char c, int shift_length) |
| 70 | +{ |
| 71 | + if (c >= 'A' && c <= 'Z') |
| 72 | + { |
| 73 | + return (((c - 'A' + (26 - shift_length)) % 26) + 'A'); |
| 74 | + } |
| 75 | + else if (c >= 'a' && c <= 'z') |
| 76 | + { |
| 77 | + return (((c - 'a' + (26 - shift_length)) % 26) + 'a'); |
| 78 | + } |
| 79 | + |
| 80 | + // In case of non-alpha characters, return as it is. |
| 81 | + return c; |
| 82 | +} |
0 commit comments