PHP base64编码丢弃错误答案



我目前正在一个网站上工作,必须实现一个web-socket服务器。我使用PHP使服务器。我从客户端响应中提取一个Sec-websocket-key,然后使用PHP sha1()命令对其进行散列。

问题是,当我想要base64_encode时,它会给出一个不正确的接受密钥,这是一个错误。base64_encode的指挥有变化吗?

谢谢你的回答!

这只是一个测试代码,它不允许多个客户端:

$address = "127.0.0.1";
$port = 9000;
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($sock, $address, $port);
socket_listen($sock);
$client = socket_accept($sock);
$handshake = Array();
$response = socket_read($client, 1024);
$handshake = split("rn", $response);
$socketKey = split(" ", $handshake[11]);
$rawAccept =  socketKey[1] . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
$rawAccept = str_replace(" ", "", $rawAccept);
$rawSha1Accept = sha1($rawAccept);
$accept = base64_encode($rawSha1Accept);
$upgrade = "HTTP/1.1 101 Switching Protocolsrn" .
            "Upgrade: websocketrn" .
            "Connection: Upgradern" .
            "Sec-WebSocket-Accept: $acceptrnrn";
socket_write($client, $upgrade, 1024);

函数sha1()已经对哈希值进行了编码,因此您应该在编码之前计算二进制哈希值:

$rawSha1Accept = sha1($rawAccept, true); // Note the second parameter
$accept = base64_encode($rawSha1Accept);

我认为错误可能在这一行:

$rawAccept =  socketKey[1] . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";

我认为socketKey[1]应该就是socketKey,但是我在下面写了一些未经测试的代码,这些代码应该可以帮助您了解如何获取密钥并创建正确的接受密钥。

$address = "127.0.0.1";
$port = 9000;
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($sock, $address, $port);
socket_listen($sock);
$client = socket_accept($sock);
$response = socket_read($client, 1024);
if (preg_match("/Sec-WebSocket-Key: (.*)rn/", $response, $match))
{
    $key = $match[1];
}
$sha = sha1($key . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", true);
$acccept = base64_encode($sha);
$upgrade = "HTTP/1.1 101 Switching Protocolsrn" .
        "Upgrade: websocketrn" .
        "Connection: Upgradern" .
        "Sec-WebSocket-Accept: $acceptrnrn";
socket_write($client, $upgrade, 1024);

相关内容

  • 没有找到相关文章

最新更新