[英]XOR encryption Javascript and PHP fails with some keys
I'm trying to crypt/decrypt a $session_key string, generated by random function, in PHP and Javascript. 我正在尝试使用PHP和Javascript加密/解密由随机函数生成的$ session_key字符串。 It works but not with all strings.
它有效,但不适用于所有字符串。 With some $session_key, as in example, the result it's different.
对于某些$ session_key,例如,结果是不同的。 You can see the result opening the browser console.
您可以打开浏览器控制台查看结果。
<?php
function xor_this($str, $key) {
$result = '';
for ($i = 0; $i < strlen($str); $i++) {
$tmp = $str[$i];
for ($j = 0; $j < strlen($key); $j++) {
$tmp = chr(ord($tmp) ^ ord($key[$j]));
}
$result .= $tmp;
}
return $result;
}
#session_key generated by substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 40)
$session_key = 'h9PYAE6KceX5g7081SnjCFBpVfux3bRtmdyDWwHq';
$password = '9b06a9342b5ac4a825088a0f0c2a2e7cc091393f';
echo xor_this($session_key, $password);
?>
<html>
<script>
function xor_this(str,key)
{
var xor = "";
for (var i = 0; i < str.length; ++i) {
tmp = str[i];
for(var j = 0; j < key.length; ++j) {
tmp = String.fromCharCode(tmp.charCodeAt(0) ^ key.charCodeAt(j));
}
xor += tmp;
}
return xor;
}
var session_key = '<?php echo $session_key?>';
var password = '<?php echo $password?>';
console.log(xor_this(session_key,password));
</script>
</html>
With the given $session_key
the result is the same from PHP and JavaScript. 使用给定的
$session_key
,结果与PHP和JavaScript相同。
PHP produces: g6_VNJ9DljW:h8?7>\\aeLIMYizw<m]{bkvKXxG~
PHP产生:
g6_VNJ9DljW:h8?7>\\aeLIMYizw<m]{bkvKXxG~
JavaScript produces: g6_VNJ9DljW:h8?7>\\aeLIMYizw<m]{bkvKXxG~
JavaScript产生:
g6_VNJ9DljW:h8?7>\\aeLIMYizw<m]{bkvKXxG~
Note that the <
would start a new HTML tag and the browser won't show the rest of the output on the page. 请注意,
<
将启动一个新的HTML标记,浏览器将不会在页面上显示其余的输出。 You have to use "view source" to see it, or make the program to call htmlspecialchars
before outputting the result. 您必须使用“查看源代码”来查看它,或者使程序在输出结果之前调用
htmlspecialchars
。
This isn't much of an encryption by the way: a long password doesn't give any extra protection since all of the chars are XORed together always. 顺便说一下,这并不是什么加密操作:长密码并不能提供任何额外的保护,因为所有字符总是被XOR在一起。 For example
$password=chr(15)
gives you the same results as the current password. 例如,
$password=chr(15)
给出的结果与当前密码相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.