[gameprogrammer] Re: XOR Problem
- From: "Dave Slutzkin" <daveslutzkin@xxxxxxxxxxx>
- To: gameprogrammer@xxxxxxxxxxxxx
- Date: Mon, 07 May 2007 14:25:24 +1000
On Sun, 6 May 2007 16:36:34 -0300, "Edilson Vasconcelos de Melo Junior"
<dirso@xxxxxxxxxxxxxxxxxx> said:
> for (string::iterator i = Text.begin(); i != Text.end(); i++)
>
> {
>
> letter = code | *i;
Shouldn't this line be:
letter = code ^ *i;
You still want to xor it to get it back to its original state, that's
the whole point.
Have a look at the attached one for a cleaned up version of your code.
Dave.
--
Dave Slutzkin
Melbourne, Australia
daveslutzkin@xxxxxxxxxxx
#include <iostream>
#include <string>
using namespace std;
string
encrypt(
const string& password,
const string& plainText)
{
unsigned short int code = 0;
for (string::const_iterator i = password.begin(), end = password.end();
i != end; ++i)
{
code ^= *i;
}
string encrypted_text;
for (string::const_iterator i = plainText.begin(), end = plainText.end();
i != end; ++i)
{
const unsigned short int plain_letter = *i;
const unsigned short int encrypted_letter = plain_letter ^ code;
encrypted_text.push_back(encrypted_letter);
code ^= plain_letter;
}
return encrypted_text;
}
string
decrypt(
const string& password,
const string& encryptedText)
{
unsigned short int code = 0;
for (string::const_iterator i = password.begin(), end = password.end();
i != end; ++i)
{
code ^= *i;
}
string plain_text;
for (string::const_iterator i = encryptedText.begin(),
end = encryptedText.end(); i != end; ++i)
{
const unsigned short int encrypted_letter = *i;
const unsigned short int plain_letter = code ^ encrypted_letter;
plain_text.push_back(plain_letter);
code ^= plain_letter;
}
return plain_text;
}
int
main(int argc, char* argv[])
{
string s1 = "Teste do Xor do Dirso";
cout << "s1: " << s1 << endl;
string s2 = encrypt("OK", s1);
cout << "s2: " << s2 << endl;
string s3 = decrypt("OK", s2);
cout << "s3: " << s3 << endl;
return 0;
}
- Follow-Ups:
- [gameprogrammer] RES: Re: XOR Problem
- From: Edilson Vasconcelos de Melo Junior
- References:
- [gameprogrammer] XOR Problem
- From: Edilson Vasconcelos de Melo Junior
Other related posts:
- » [gameprogrammer] XOR Problem
- » [gameprogrammer] Re: XOR Problem
- [gameprogrammer] RES: Re: XOR Problem
- From: Edilson Vasconcelos de Melo Junior
- [gameprogrammer] XOR Problem
- From: Edilson Vasconcelos de Melo Junior