Here is a simple example of using the XOR encryption mentioned above. It asks for a string to be encrypted, then asks for a key to be used to encrypt the data. It then displays the original string, the encrypted string and the decrypted (matching the original) string. This is only meant as a very basic example to show how it might/could be done (so no flames about it being pathetic/unsecure or whatever please).
Code:
#include <string>
#include <iostream>
#include <algorithm>
#include <functional>
template<typename T>
struct exclusive_or : public std::binary_function<T,T,T>
{
T operator() (T lhs, T rhs) const
{
return lhs ^ rhs;
}
};
int main()
{
std::string data, key, temp;
// Get string and key from user
std::cout << "Enter string to encrypt: ";
std::getline(std::cin,data);
std::cout << "Enter key: ";
std::getline(std::cin,temp);
// Ensure key is at least as long as data to be encrypted.
// This is needed because of the transform call below
key = temp;
while( key.length() < data.length() ) key+= temp;
std::cout << "Original string: " << data << std::endl;
// Encrypt string and output
std::transform(data.begin(),data.end(),key.begin(),data.begin(),exclusive_or<char>());
std::cout << "Encrypted string: " << data << std::endl;
// Decrypt string and output using same procedure
std::transform(data.begin(),data.end(),key.begin(),data.begin(),exclusive_or<char>());
std::cout << "Decrypted string: " << data << std::endl;
return 0;
}
Something I'd like to know... why the heck isn't there some kind of a std::exclusive_or<> function adapter? Seems it would be handy to have.