1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
#include <iostream> #include <string> using namespace std; // Function to encrypt a message using Caesar cipher string encrypt(const string& message, int shift) { string encryptedMessage = message; for (char& c : encryptedMessage) { if (isalpha(c)) { char base = islower(c) ? 'a' : 'A'; c = (c - base + shift) % 26 + base; } } return encryptedMessage; } // Function to decrypt a message using Caesar cipher string decrypt(const string& message, int shift) { return encrypt(message, 26 - shift); // Decryption is encryption with (26 - shift) } int main() { string message; int shift; cout << "Enter the message to encrypt: "; getline(cin, message); cout << "Enter the shift value (1-25): "; cin >> shift; if (shift < 1 || shift > 25) { cout << "Invalid shift value. It should be between 1 and 25." << endl; return 1; } // Encrypt the message string encryptedMessage = encrypt(message, shift); cout << "Encrypted message: " << encryptedMessage << endl; // Decrypt the message string decryptedMessage = decrypt(encryptedMessage, shift); cout << "Decrypted message: " << decryptedMessage << endl; return 0; } |
Explanation:
- Caesar Cipher Encryption (
encrypt
):- The
encrypt
function shifts each letter in the input message by a specified number of positions in the alphabet. - It loops through each character in the message:
- If the character is a letter, it calculates its new position by shifting it and wraps around the end of the alphabet using modulo arithmetic.
- The character is then updated with the new shifted value.
Advertisement - Non-alphabetic characters remain unchanged.
Advertisement - The
- Caesar Cipher Decryption (
decrypt
):- The
decrypt
function reverses the encryption by shifting in the opposite direction. - It uses the same
encrypt
function but shifts by26 - shift
to undo the encryption.
- The
- Main Function (
main
):- Prompts the user to enter a message and a shift value.
- Encrypts the message using the provided shift value.
- Prints the encrypted message.
- Decrypts the encrypted message using the same shift value and prints the decrypted message.
Advertisement
Possible Enhancements:
- Error Handling: Add more robust error handling for input validation and edge cases.
- Different Ciphers: Implement other encryption algorithms (e.g., Vigenère cipher, RSA) for more secure encryption.
- File Handling: Extend the program to read from and write to files for encrypting and decrypting larger texts.
- GUI Interface: Develop a graphical user interface (GUI) for a more user-friendly experience.