I looked at some of the XOR examples and am unable to find an answer.
This is the code I'm using for PHP:
for($i=0;$i<strlen($text);)
{
for($j=0;($j<strlen($key) && $i<strlen($text));$j++,$i++)
{
$outText .= $text{$i} ^ $key{$j};
//echo 'i='.$i.', '.'j='.$j.', '.$outText{$i}.'<br />'; //for debugging
}
}
And the resulting code for decryption in C++:
for (int i = 0; i < original.size();)
{
for (int j = 0; (j < key.size() && i < original.size()); j++, i++)
{
decrypted += encrypted[i] ^ key[j];
}
}
I'm having trouble getting around the need for the plaintext's size (std::string original in this case).
Without, hopefully, drastically changing the way I do the algorithm, is there a way around this?
Thanks in advance!
The ciphertext and plaintext are the same length. So either size will do.
You also do not need two levels of loop nest to do this in PHP or C++.
Your code should look more like this:
$textlen = strlen($text);
$keylen = strlen($key);
for ($i = 0; $i < $textlen; $i++)
{
$outText .= chr( ord( $text{$i} ) ^ ord ( $key{$i % $keylen} ) );
}
I answered another question on XOR encryption here, since it seems to be all the rage these days.
BTW, if you try to backport this PHP code back to C++, be aware that (unlike PHP), strlen
stops at ASCII NULs, and won't do what you want. You're better off using either std::string
or vector<char>
for the C++ version. (See link above for my C++ code.)