XOR A String In PHP With Key Is An Integer

折月煮酒 提交于 2020-01-06 06:57:10

问题


I am making a HTTP POST request to my server from my C++ application via sockets, I will be XORing the POST values from my C++ application before they are sent to my server. Once these XORed POST values are sent to my server I am going to need to be able to 'decrypt' them before processing the values on my server.

My C++ application currently is XORing strings like so

char *XOR(char *string)
{
    //key = 0x10
    char buffer[1000] = { 0 };
    for (int i = 0; i < strlen(string); i++)
        buffer[i] = string[i] ^ 0x10;
    buffer[strlen(string)] = 0x00;
    return buffer;
    //yes I know, this function could be written much better. But that is not the point of this question...
}

Now in PHP I am using this function to XOR a string

function XOR($string, $key)
{
    for($i = 0; $i < strlen($string); $i++) 
        $string[$i] = ($string[$i] ^ $key[$i % strlen($key)]);
    return $string;
}

I have tried calling it like this

$decryptedValue = XOR($_POST['postParam1'], "16");

And like this

$decryptedValue = XOR($_POST['postParam1'], 16);

But the value stored in $decryptedValue never matches up with the XORed value sent from C++ application

For example if I XOR "test" in my C++ application with key as 0x10 the return value is

0x64, 0x75, 0x63, 0x64

But If I XOR "test" on my server the return value is

0x45, 0x53, 0x42, 0x42

回答1:


You need to convert your character to an integer with ord, then XOR it with $key (not using key as a string), then convert it back to a character with chr. Otherwise, it XOR's the string value with a string containing "16", which clearly doesn't achieve the same result.

function encrypt($string, $key)
{
    for($i = 0; $i < strlen($string); $i++) 
            $string[$i] = chr(ord($string[$i]) ^ $key);
    return $string;
}

(My version of PHP thinks XOR is a keyword, so I renamed the function to encrypt).

To test:

encrypt("test", 16);


来源:https://stackoverflow.com/questions/48899919/xor-a-string-in-php-with-key-is-an-integer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!