PHP base64 编码丢弃不正确的答案

PHP base64 encoding drops incorrect answer

我目前正在开发一个网站,该网站必须实施网络套接字服务器。我正在使用 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("\r\n", $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 Protocols\r\n" .
            "Upgrade: websocket\r\n" .
            "Connection: Upgrade\r\n" .
            "Sec-WebSocket-Accept: $accept\r\n\r\n";

socket_write($client, $upgrade, 1024);

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

$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: (.*)\r\n/", $response, $match))
{
    $key = $match[1];
}

$sha = sha1($key . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", true);
$acccept = base64_encode($sha);

$upgrade = "HTTP/1.1 101 Switching Protocols\r\n" .
        "Upgrade: websocket\r\n" .
        "Connection: Upgrade\r\n" .
        "Sec-WebSocket-Accept: $accept\r\n\r\n";

socket_write($client, $upgrade, 1024);

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

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