在 PHP 中使用 XOR 加密/解密

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14673551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:46:11  来源:igfitidea点击:

Encrypt/decrypt with XOR in PHP

phpencryption

提问by JoeNguyen

I am studying encryption. And I got a problem like this:

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

After I XOR plaintext with a key, I get a crypt, "010e010c15061b4117030f54060e54040e0642181b17", as hex type. If I want to get plaintext from this crypt, what should I do in PHP?

在我用密钥对明文进行异或之后,我得到一个 crypt,“010e010c15061b4117030f54060e54040e0642181b17”,作为十六进制类型。如果我想从这个 crypt 中获取明文,我应该在 PHP 中做什么?

I tried convert it to string/int and after that take them to XOR with the key (three letters). But it doesn't work.

我尝试将其转换为字符串/整数,然后将它们与密钥(三个字母)进行异或。但它不起作用。

This is the code:

这是代码:

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, '=================';

And this is the result:

这是结果:

This is the test-------------

PHP Notice: Uninitialized string offset: 29 in C:\ Users\Administrator\Desktop\test.php on line 210 PHP Stack trace: PHP 1. {main}() C:\Users\Administrator\Desktop\test.php:0 PHP 2. xor_this() C:\Users\Administrator\Desktop\test.php:239

Notice: Uninitialized string offset: 29 in C:\Users\Administrator\Desktop\test.p hp on line 210

Call Stack: 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++++++++

This is zs$fs?=================

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

PHP 注意:未初始化的字符串偏移量:29 in C:\Users\Administrator\Desktop\test.php on line 210 PHP Stack trace: PHP 1. {main}() C:\Users\Administrator\Desktop\test.php:0 PHP 2. xor_this() C:\Users\Administrator\Desktop\test.php:239

注意:未初始化的字符串偏移量:29 in C:\Users\Administrator\Desktop\test.p hp on line 210

调用堆栈: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?==================

Why? The "UBE^A?WEAVA?WEAV@?WEARAFWECWB++++++++" is the result, which I got trouble in my real work.

为什么?结果是“UBE^A?WEAVA?WEAV@?WEARAFWECWB++++++++”,我在实际工作中遇到了麻烦。

回答by One Man Crew

Try this:

尝试这个:

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

Basically to revert text back (even numbers are in) you can use the same function:

基本上要恢复文本(偶数在),您可以使用相同的功能:

$textToObfuscate = "Some Text 12345";
$obfuscatedText = xor_this($textToObfuscate);
$restoredText = xor_this($obfuscatedText);

回答by lalala

Even easier:

更简单:

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

回答by Stalingrad

Based on the code above i created 2 functions to xor encode a JSON string using javascript and then decode it on server side using PHP.

基于上面的代码,我创建了 2 个函数来使用 javascript 对 JSON 字符串进行异或编码,然后使用 PHP 在服务器端对其进行解码。

!!! Important:If you will have characters different from ASCII(like Chinese, Cyrillic, Symbols...) in your JSON string, you must eitherwrite some code in PHP or JS to fix how these characters are encoded/decoded (ord/chr in PHP produce different results in comparison with JS charCodeAt/String.fromCharCode) orjust base64_encode the JSON string and after that xor encode it.

!!!重要提示:如果你会在你的JSON字符串有不同的ASCII(如china,西里尔字母,符号...)字符,则必须要么写在PHP或JS的一些代码来解决这些字符是如何编码/解码(ORD / CHR在与 JS charCodeAt/String.fromCharCode) 相比,PHP 会产生不同的结果,或者只是 base64_encode JSON 字符串,然后对其进行异或编码。

Personally i use xor_string(base64_encode(JSON.stringify(object)), 'xor_key')in JS and on PHP side:

我个人xor_string(base64_encode(JSON.stringify(object)), 'xor_key')在 JS 和 PHP 端使用:

$json = json_decode(base64_decode(
                        xor_string(file_get_contents("php://input"), 'xor_key')
                    ),
        true);

PHP:

PHP:

function xor_string($string, $key) {
    $str_len = strlen($string);
    $key_len = strlen($key);

    for($i = 0; $i < $str_len; $i++) {
        $string[$i] = $string[$i] ^ $key[$i % $key_len];
    }

    return $string;
}

Javascript:

Javascript:

function xor_string(string, key) {
    string = string.split('');
    key = key.split('');
    var str_len = string.length;
    var key_len = key.length;
    var String_fromCharCode = String.fromCharCode;

    for(var i = 0; i < str_len; i++) {
        string[i] = String_fromCharCode(string[i].charCodeAt(0) ^ key[i % key_len].charCodeAt(0));
    }

    return string.join('');
}