首页 > 解决方案 > PHP中的Xor函数对应于C#中的Xor函数

问题描述

我需要在 PHP 中编写一个函数,该函数输出与下面 C# 中的结果相同的结果。

C#

public void Criptami()
   {
       szEncryptionKey = 200;
       szPlainText = input.text;
       StringBuilder szInputStringBuild = new StringBuilder(szPlainText);
       StringBuilder szOutStringBuild = new StringBuilder(szPlainText.Length);
       char Textch;
       for (int iCount = 0; iCount < szPlainText.Length; iCount++)
       {
           Textch = szInputStringBuild[iCount];
           Textch = (char)(Textch ^ szEncryptionKey);
           szOutStringBuild.Append(Textch);
       }
       Debug.Log(szOutStringBuild.ToString());
   }

现在我已经尝试使用我在 Stackoverflow 上的另一个讨论中找到的函数(在 PHP 中使用 XOR 加密/解密),但是输入相同,最终输出不同。

function xor_this($string) {

    // Let's define our key here
    $key = (200);

    // Our plaintext/ciphertext
    $text = $string;

    // Our output text
    $outText = '';

    // Iterate through each character
    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
        }
    }
    return $outText;
}

我得到了 C# 中的一段代码,但就我能收集到的信息而言——尽管我对 C# 的了解几乎不存在——在我看来,它应该以完全相同的方式运行吗?

感谢一百万您的时间!

编辑:我添加了输入和输出值

PHP 输入:ciao 输出:QYQ]

C# 输入: ciao 输出:«¡©§

标签: c#phpxor

解决方案


出于某种原因,您正在迭代strlen($key). 我猜你不想那样做。以下是我的 PHP 无能的自我管理:

function xor_this($string) {

// Let's define our key here
$key = (200);

// Our plaintext/ciphertext
$text = $string;

// Our output text
$outText = '';

// Iterate through each character
for($i=0; $i<strlen($text); $i++)
{
    $char = substr($text, $i, 1);
    $char = chr(ord($char) ^ $key);
    $outText .= $char;
}

return $outText;
}

这个SO 答案的帮助下。如另一个答案所示,这可以更简洁地完成:

function xor_this($string)
{
    $key = (200);
    for($i = 0; $i < strlen($string); $i++) 
            $string[$i] = chr(ord($string[$i]) ^ $key);

    return $string;
}

推荐阅读