#include <iostream>
#include <iomanip>
#include <algorithm>
using namespace std;
struct Encryptor {
const int key;
int count;
Encryptor( int key ) : key(key), count(0) {
}
char operator() ( char ch ) {
ch = (ch ^ key) + count;
++count;
return ch;
}
};
struct Decryptor {
const int key;
int count;
Decryptor( int key) : key(key), count(0) {
}
char operator() ( char ch ) {
ch = (ch - count) ^ key;
++count;
return ch;
}
};
void hexDump( const string& str ) {
unsigned track = 0;
unsigned len = str.length();
unsigned lineStart = 0;
unsigned nearest16 = ((len + 16) / 16) * 16;
for ( unsigned i = 0; i < nearest16; ++i ) {
if ( i < len )
cout << setw( 2 ) << setfill( '0' ) << hex << uppercase <<
(unsigned)reinterpret_cast<const unsigned char&>(str[i]) << ' ';
else
cout << " ";
track ++;
if ( track == 16 ) {
cout << " ";
track = 0;
for ( unsigned j = 0; j < 16 && lineStart + j < len; ++j ) {
unsigned char ch = reinterpret_cast<const unsigned char&>( str[lineStart + j] );
if ( ch < 32 || ch >= 127 )
ch = '.';
cout << ch;
}
cout << endl;
lineStart = i+1;
}
}
}
int main() {
int key = 0x01;
string line = "The quick brown fox jumps over the lazy dog.";
cout << "Input:" << endl;
hexDump( line );
cout << endl;
cout << "Encrypted output:" << endl;
transform( line.begin(), line.end(), line.begin(), Encryptor( key ) );
hexDump( line );
cout << endl;
cout << "Decrypted output:" << endl;
transform( line.begin(), line.end(), line.begin(), Decryptor( key ) );
hexDump( line );
cout << endl;
}