Untitled
unknown
plain_text
9 days ago
3.1 kB
3
Indexable
Never
#include <iostream> #include <string> using namespace std; // Function to convert a string to uppercase // This function changes each lowercase letter to uppercase manually. string convertToUpperCase(string inputText) { for (int i = 0; i < inputText.size(); i++) { if (inputText[i] >= 'a' && inputText[i] <= 'z') { inputText[i] = inputText[i] - 'a' + 'A'; // Manual conversion from lowercase to uppercase } } return inputText; } // Function to expand the key to match the length of the input message. // The key is repeated until its length equals the message length. string extendKey(string message, string keyword) { string extendedKey = keyword; // Start with the original key int messageLength = message.size(); int keyLength = keyword.size(); // Repeat the keyword to make it match the message length for (int i = 0; i < messageLength - keyLength; i++) { extendedKey += keyword[i % keyLength]; // Adding characters cyclically from the keyword } return extendedKey; } // Encrypt the input message using the extended key with a basic Vigenère cipher string encryptMessage(string message, string extendedKey) { string encryptedMessage = ""; // Loop through each character in the message and apply encryption formula for (int i = 0; i < message.size(); i++) { char encryptedChar = (message[i] - 'A' + extendedKey[i] - 'A') % 26 + 'A'; // Encrypt using Vigenère cipher encryptedMessage += encryptedChar; // Add the encrypted character to the result } return encryptedMessage; } // Decrypt the encrypted message using the extended key to retrieve the original message string decryptMessage(string encryptedMessage, string extendedKey) { string decryptedMessage = ""; // Loop through the encrypted message and apply the decryption formula for (int i = 0; i < encryptedMessage.size(); i++) { char decryptedChar = (encryptedMessage[i] - extendedKey[i] + 26) % 26 + 'A'; // Decrypt using Vigenère cipher decryptedMessage += decryptedChar; // Add the decrypted character to the result } return decryptedMessage; } // Main function to demonstrate the encryption and decryption process int main() { string inputMessage = "HELLOVIGENERE"; // Original message to encrypt string keyword = "KEYWORD"; // Key used for encryption // Convert message and key to uppercase (for consistency) inputMessage = convertToUpperCase(inputMessage); keyword = convertToUpperCase(keyword); // Generate an extended key that matches the length of the message string extendedKey = extendKey(inputMessage, keyword); // Encrypt the message string encryptedMessage = encryptMessage(inputMessage, extendedKey); cout << "Encrypted Message: " << encryptedMessage << endl; // Decrypt the message back to the original text string decryptedMessage = decryptMessage(encryptedMessage, extendedKey); cout << "Decrypted Message: " << decryptedMessage << endl; return 0; }
Leave a Comment