Doing an XOR on a string?

Hi,

I am doing an XOR on a string in an objective-c application, the strings are UTF-8, unicode.

Now I'm trying to 'decrypt' the strings again in PHP, but it is not working. I have the following which works on ASCII characters I guess. It would be difficult to get the objective-c part to work in ascii only, so I'm looking to modify the PHP part to work with UTF-8. I tried just getting rid of ord() and replacing chr() with a unicode variant, but no luck.

Thanks

function XOREncryption($input)
{
    $crypt_key = "ABCDEFG";
 
    $vlen = strlen($input);
    $klen = strlen($crypt_key);
    $k = 0;
 
    for ($v = 0; $v < $vlen; $v++) {
            
        $c = ord($input[$v]) ^ ord($crypt_key[$k]);
        $input[$v] = chr($c);
 
        $k++;
        if ($k == $klen) {
            $k = 0;
        }
    }
 
    return $input;            
}

Open in new window

DJ_AM_JuiceboxAsked:
Who is Participating?
 
Michael701Connect With a Mentor Commented:
you should be able to have this a litle cleaner ^ works on characters just as well as numbers

        $input[$v] = $input[$v] ^ $crypt_key[$k];

I tested this and it works


function XOREncryption($input)
{
    $crypt_key = "ABCDEFG";
 
    $vlen = strlen($input);
    $klen = strlen($crypt_key);
    $k = 0;
 
    for ($v = 0; $v < $vlen; $v++) {
            
         $input[$v] = $input[$v] ^ $crypt_key[$k];
 
        $k++;
        if ($k == $klen) {
            $k = 0;
        }
    }
 
    return $input;            
}
 
$message=XOREncryption("hello world");
echo "ecrypt: ". $message ."<br />\n";
$original=XOREncryption($message);
echo "original: ".$original ."<br />\n";

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.