PHP中带键的字符串异或是整数 [英] XOR A String In PHP With Key Is An Integer
问题描述
我正在通过 sockets
从我的 C++
应用程序向我的服务器发出 HTTP
POST
请求,我会在将 C++
应用程序中的 POST
值发送到我的服务器之前,对它们进行 XORing
.一旦这些 XORed
POST
值发送到我的服务器,我将需要能够在处理我的服务器上的值之前解密"它们.
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.
我的 C++
应用程序目前是 XORing
strings
就像这样
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...
}
现在在 PHP
我使用这个函数来 XOR
一个 string
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;
}
我试过这样称呼它
$decryptedValue = XOR($_POST['postParam1'], "16");
像这样
$decryptedValue = XOR($_POST['postParam1'], 16);
但是存储在 $decryptedValue
中的值永远不会与 C++
应用程序发送的 XORed
值匹配
But the value stored in $decryptedValue
never matches up with the XORed
value sent from C++
application
例如,如果我 XOR
"test"
在我的 C++
应用程序中使用键作为 0x10
返回值是
For example if I XOR
"test"
in my C++
application with key as 0x10
the return value is
0x64, 0x75, 0x63, 0x64
但是如果我在我的服务器上 XOR
"test"
返回值是
But If I XOR
"test"
on my server the return value is
0x45, 0x53, 0x42, 0x42
推荐答案
你需要用 ord
把你的字符转换成整数,然后用 $key
(不使用键作为字符串),然后将其转换回带有 chr
的字符.否则,它将字符串值与包含 "16"
的字符串进行 XOR,这显然不会达到相同的结果.
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;
}
(我的 PHP 版本认为 XOR 是关键字,所以我将函数重命名为 encrypt).
(My version of PHP thinks XOR is a keyword, so I renamed the function to encrypt).
测试:
encrypt("test", 16);
这篇关于PHP中带键的字符串异或是整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!