XOR Encryption in C++
Hello everyone, in this tutorial, we are going to learn about XOR Encryption in C++. XOR encryption is difficult to crack by the brute-force technique. In the brute force technique, we generate random encryption keys and match them with the right encryption key.
Algorithm
As we know, when we perform XOR operation between two values, then XOR of the resultant value and any of the previous values gives us the remaining value. For example, if XOR of a and b is c, then XOR of c and a will be b, and XOR of c and b will be a. XOR encryption method uses the above property.
Let’s say we have a string and we want to encrypt our string using XOR encryption. To do this, we will first define an encryption key randomly. It can be any character value. Then we will perform XOR operation on every character of our string. Thus we will have our encrypted string. We can get the original string again by performing XOR operation on every character of the encrypted string.
C++ implementaion of XOR encryption
Here is the C++ implementation of the above method. Have a look at the below code.
#include <iostream> using namespace std; string xor_operation(string inp_string) { char encryption_key = 'A'; string out_string = ""; int i = 0; while(i < inp_string.length()) { out_string += inp_string[i] ^ encryption_key; i++; } return out_string; } int main() { string inp_string = "codespeedy"; cout << "Original data: "; cout << inp_string << endl; string encrypted_string = xor_operation(inp_string); cout << "Encrypted data: "; cout << encrypted_string << endl; string decrypted_string = xor_operation(encrypted_string); cout << "Decrypted (original) data: "; cout << decrypted_string << endl; return 0; }
Output:
Original data: codespeedy Encrypted data: ".%$21$$%8 Decrypted (original) data: codespeedy
In the above example, our encryption key is ‘A’. We can change it to any value. However, we need to know the encryption key to decrypt the string.
As you can see, we can easily encrypt and decrypt our data using simple XOR encryption.
Also read: Implementation of Null Cipher in C++
Leave a Reply