XOR A String In PHP With Key Is an Integer

XOR A String In PHP With Key Is An Integer

我正在通过 sockets 从我的 C++ 应用程序向我的服务器发出 HTTP POST 请求,我将 XORing [=18] =] 值从我的 C++ 应用程序发送到我的服务器之前。一旦这些 XORed POST 值被发送到我的服务器,我将需要能够 'decrypt' 它们才能在我的服务器上处理这些值。

我的 C++ 申请目前是 XORing strings 像这样

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...
}

现在 PHP 我正在使用这个函数 XOR string

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

我试过这样称呼它

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

像这样

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

但是 $decryptedValue 中存储的值永远不会与 C++ 应用程序

发送的 XORed 值匹配

例如,如果我 XOR "test" 在我的 C++ 应用程序中,键为 0x10,则 return 值为

0x64, 0x75, 0x63, 0x64

但是如果我 XOR "test" 在我的服务器上 return 值是

0x45, 0x53, 0x42, 0x42

您需要使用 ord 将您的字符转换为整数,然后使用 $key 将其异或(不将键用作字符串),然后使用 [=14] 将其转换回字符=].否则,它将字符串值与包含 "16" 的字符串进行异或,这显然不会获得相同的结果。

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

(我的版本PHP认为XOR是关键字,所以我把函数重命名为encrypt)

测试:

encrypt("test", 16);