我尝试在我的javascript客户端使用rc4算法加密数据,并用我的php服务器解密它。我发现这个代码here。我使用单词“测试”作为我的密钥用于测试目的。当我加密text
,然后记录它时,我得到奇怪的字符(可能是加密),但当我试图在我的php服务器解密它时,我确实得到了相同的字符,但有额外或更少的字符。示例:
JavaScript客户端控制台:
text before encrypting: {"data":"yo, server"}
background.js:958 encryptedText: ÕCpK_ô72O1×½ËûÂ$ó
background.js:907 sent data: "ÕCpK_\u001fô72O1×½ËûÂ$ó"
字符串
PHP控制台:
"ÕCpK_\u001fô72O1×½ËûÂ$ó""\u00d5\u00adCp\u0094K_\u001f\u00f472O1\u00d7\u0082\u00bd\u00cb\u00fb\u00c2$\u00f3"
型
我在我的客户端javascript
(Chrome扩展)中使用以下rc4函数:
// Send data
function sendWebSocketData(data) {
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(data))
console.log('sent data: ' + JSON.stringify(data))
} else {
console.log('DEBUG: WebSocket connection is not open.')
}
}
function rc4(key, str) {
var s = [], j = 0, x, res = '';
for (var i = 0; i < 256; i++) {
s[i] = i;
}
for (i = 0; i < 256; i++) {
j = (j + s[i] + key.charCodeAt(i % key.length)) % 256;
x = s[i];
s[i] = s[j];
s[j] = x;
}
i = 0;
j = 0;
for (var y = 0; y < str.length; y++) {
i = (i + 1) % 256;
j = (j + s[i]) % 256;
x = s[i];
s[i] = s[j];
s[j] = x;
res += String.fromCharCode(str.charCodeAt(y) ^ s[(s[i] + s[j]) % 256]);
}
return res;
}
let text = { data: 'yo, server' }
console.log('text before encrypting: ' + JSON.stringify(text))
encryptedText = rc4('test', JSON.stringify(text))
console.log('encryptedText: ' + encryptedText)
sendWebSocketData(encryptedText)
型
下面是我的php
服务器的rc4函数:
public function onMessage(ConnectionInterface $from, $msg)
{
// Process the received message (handle JSON data)
rc4('test', $msg);
echo $msg;
$decoded = json_decode($msg, true);
echo json_encode($decoded);
}
function rc4($key, $str)
{
$s = array();
for ($i = 0; $i < 256; $i++) {
$s[$i] = $i;
}
$j = 0;
for ($i = 0; $i < 256; $i++) {
$j = ($j + $s[$i] + ord($key[$i % strlen($key)])) % 256;
$x = $s[$i];
$s[$i] = $s[$j];
$s[$j] = $x;
}
$i = 0;
$j = 0;
$res = '';
for ($y = 0; $y < strlen($str); $y++) {
$i = ($i + 1) % 256;
$j = ($j + $s[$i]) % 256;
$x = $s[$i];
$s[$i] = $s[$j];
$s[$j] = $x;
$res .= $str[$y] ^ chr($s[($s[$i] + $s[$j]) % 256]);
}
return $res;
}
型
1条答案
按热度按时间csbfibhn1#
我通过首先将其编码为
base64
来修复它php:
字符串
JavaScript:
型