c# - 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 输出:«¡©§
解决方案
出于某种原因,您正在迭代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;
}
推荐阅读
- amazon-web-services - AWS:使用 Cloudsearch 提取文本
- sql - 返回 SQL Server 上 DATETIME2(2) 的最小值和最大值
- mobaxterm - MobaXterm:如何在不使用已保存会话的情况下打开 ssh 浏览器
- python - 如何在 elasticsearch python 低级客户端中指定 index.mapping.ignore_malformed?
- javascript - React Native Expo - 无法将数据发送到 php 文件
- python-2.7 - 将整数与浮点数相乘会产生不好的结果 Python 2.7
- javascript - 返回带有布尔值的局部视图
- python - 如何从python中的数组字典中获取值?
- oauth - 通过 nodemailer 中的 gmail oauth 发送电子邮件需要哪个范围?
- android - 预选赛屏幕尺寸小不适用于尺寸