在PHP中使用XOR加密/解密

Joe*_*yen 14 php encryption

我正在研究加密.我遇到了这样的问题:

在我用密钥对XOR明文进行后,我得到一个密码,"010e010c15061b4117030f54060e54040e0642181b17",作为十六进制类型.如果我想从这个地穴获取明文,我该怎么做PHP?

我尝试将它转换为string/int,之后用键(三个字母)将它们转换为XOR.但它不起作用.

这是代码:

function xor_this($string) {

    // Let's define our key here
    $key = 'fpt';

    // 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); $j++,$i++)
        {
            $outText .= ($text[$i] ^ $key[$j]);
            //echo 'i=' . $i . ', ' . 'j=' . $j . ', ' . $outText{$i} . '<br />'; // For debugging
        }
    }
    return $outText;
}

function strToHex($string)
{
    $hex = '';
    for ($i=0; $i < strlen($string); $i++)
    {
        $hex .= dechex(ord($string[$i]));
    }
    return $hex;
}

function hexToStr($hex)
{
    $string = '';
    for ($i=0; $i < strlen($hex)-1; $i+=2)
    {
        $string .= chr(hexdec($hex[$i].$hex[$i+1]));
    }
    return $string;
}

$a = "This is the test";
$b = xor_this($a);
echo xor_this($b), '-------------';
//
$c = strToHex($b);
$e = xor_this($c);
echo $e, '++++++++';
//
$d = hexToStr($c);
$f = xor_this($d);
echo $f, '=================';
Run Code Online (Sandbox Code Playgroud)

这就是结果:

这是测试-------------

PHP注意:未初始化的字符串偏移量:29行C:\ Users\Administrator\Desktop\test.php第210行PHP堆栈跟踪:PHP 1. {main}()C:\ Users\Administrator\Desktop\test.php:0 PHP 2. xor_this()C:\ Users\Administrator\Desktop\test.php:239

注意:未初始化的字符串偏移量:在第210行的C:\ Users\Administrator\Desktop\test.p hp中为29

调用堆栈:0.0005 674280 1. {main}()C:\ Users\Administrator\Desktop\test.php:0 0.0022 674848 2. xor_this()C:\ Users\Administrator\Desktop\test.php:23 9

UBE ^A►WEAVA►WEAV@◄WEARAFWECWB++++++++

这是zs $fs☺=================

为什么?结果是"UBE ^A►WEAVA►WEAV@◄WEARAFWECWB++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

One*_*rew 25

试试这个:

function xor_this($string) {

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

    // 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;
}
Run Code Online (Sandbox Code Playgroud)

基本上是为了恢复文本(甚至是数字)你可以使用相同的功能:

$textToObfuscate = "Some Text 12345";
$obfuscatedText = xor_this($textToObfuscate);
$restoredText = xor_this($obfuscatedText);
Run Code Online (Sandbox Code Playgroud)


小智 12

更简单:

function xor_string($string, $key) {
    for($i = 0; $i < strlen($string); $i++) 
        $string[$i] = ($string[$i] ^ $key[$i % strlen($key)]);
    return $string;
}
Run Code Online (Sandbox Code Playgroud)