In this section, we'll write a simple encryption program using symmetric encryption (AES) and XOR encryption in C/C++. This will give you hands-on experience with implementing encryption algorithms and understanding how encryption/decryption works at a low level. We'll start with a basic XOR encryption for learning purposes and then move to a more robust algorithm like AES.
XOR encryption is one of the simplest forms of encryption. It's not secure by modern cryptographic standards, but it's a great way to understand how encryption and decryption work at a basic level.
This property makes XOR useful for encryption and decryption. The key is simply XOR'd with the data during both encryption and decryption processes.
#include <iostream>
#include <string>
using namespace std;
string xorEncryptDecrypt(string data, char key) {
for (int i = 0; i < data.length(); i++) {
data[i] = data[i] ^ key;
}
return data;
}
int main() {
string data;
char key;
cout << "Enter the data to encrypt/decrypt: ";
getline(cin, data);
cout << "Enter the key (single character): ";
cin >> key;
string encryptedData = xorEncryptDecrypt(data, key);
cout << "Encrypted Data: " << encryptedData << endl;
string decryptedData = xorEncryptDecrypt(encryptedData, key);
cout << "Decrypted Data: " << decryptedData << endl;
return 0;
}
Enter the data to encrypt/decrypt: Hello, World!
Enter the key (single character): K
Encrypted Data: @4(-..%.03%0
Decrypted Data: Hello, World!
This is a simple and effective way to understand how encryption and decryption work using XOR. For actual use, however, this is not secure, and more sophisticated encryption algorithms should be used.
Now that we have a basic encryption algorithm, let's move to a more robust and secure approach. We'll implement AES encryption in C++ using the OpenSSL library. AES is widely used in modern cryptography for encrypting sensitive data, and it's much more secure than XOR encryption.
sudo apt-get install libssl-dev