javascript - 字符串异或加密因某些 key 而失败

标签 javascript encryption xor

我试图用php“加密”一个字符串(js代码),然后使用javascript对其进行解码。

这是 php 函数:

function xor_string( $text, $xorKey ) {
    $xored = '';
    $chars = str_split( $text );

    $i = 0;

    while ( $i < count( $chars ) ) {
        $xored .= chr( ord( $chars[$i] ) ^ $xorKey );
        $i++;
    }

    return $xored;
}

这是js函数:

function xor_string( str, key ) {
    var xored = "";
    for (i=0; i<str.length;i++) {
        var a = str.charCodeAt(i);
        var b = a ^ key;
        xored = xored+String.fromCharCode(b);
    }
    console.log(xored);
}

对于某些键,这种方法是双向的,但对于其他键,则失败,例如:

echo urlencode( xor_string( 'document.location.href.search', 67 ) );

返回:

%27%2C+6.%26-7m%2F%2C+%227%2A%2C-m%2B1%26%25m0%26%221+%2B

当我尝试使用 javascript 对其进行“解码”时:

var str = decodeURIComponent("%27%2C+6.%26-7m%2F%2C+%227%2A%2C-m%2B1%26%25m0%26%221+%2B");
xor_string( str, 67 );

它返回:

dohument.lohation.href.searhh

有人知道为什么会发生这种情况吗?

对于某些“键”(例如 120 等),它可以正常工作,但对于许多其他“键”,它会失败。

最佳答案

经典:-)

PHP 的 urlencode 与 JavaScript 的 encodeURIComonent 并不完全相同:它们处理空格的方式不同;一个使用 +,另一个使用 %20

你需要处理这个问题,例如phpjs offers a PHP-compliant decodeURI function .

> var phpstring = "%27%2C+6.%26-7m%2F%2C+%227%2A%2C-m%2B1%26%25m0%26%221+%2B";
> xor_string(decodeURIComponent(phpstring.replace(/\+/g, "%20")), 67 );
"document.location.href.search"

您可能会注意到,此错误仅命中使用 xor 函数(及其参数)编码为空格的字符。

关于javascript - 字符串异或加密因某些 key 而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12612747/

相关文章:

javascript - 在 webpack 4 项目中使用 Jest 会抛出 'Jest encountered an unexpected token' 错误

javascript - 使用javascript将PDF转换为DOM

Java 加密设置失败并出现 InvalidKeySpecException

encryption - 如何从私钥生成RSA公钥?

c++ - 如何使用 XOR 加密字符串而不包含奇怪的字符?

c++ - 为什么 C/C++ 中没有 ^^ 运算符?

javascript - 如何检测加壳并美化这个js

javascript - 无法弄清楚如何将导航器与 Jssor Slider 一起使用

java - AES/CFB解密

python - 什么是 Python symmetric_difference,它与 XOR 运算有何不同?