Orbit Framework 2.0.0
A high-performance asynchronous C++20 HTTP server framework.
Loading...
Searching...
No Matches
WebSocket.hpp
Go to the documentation of this file.
1#pragma once
3#include <string>
4#include <string_view>
5#include <openssl/sha.h>
6#include <openssl/evp.h>
7
8namespace orbit::http {
9namespace websocket {
10
14class Handshake {
15public:
20 static bool is_valid_client_key(std::string_view key) {
21 if (key.size() != 24 || key.substr(22) != "==") return false;
22 for (size_t i = 0; i < 22; ++i) {
23 char c = key[i];
24 bool ok = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '+' || c == '/';
25 if (!ok) return false;
26 }
27 return true;
28 }
29
35 static std::string generate_accept_key(const std::string& client_key) {
36 const std::string magic_string = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
37 std::string combined = client_key + magic_string;
38
39 unsigned char hash[SHA_DIGEST_LENGTH];
40 SHA1(reinterpret_cast<const unsigned char*>(combined.c_str()), combined.length(), hash);
41
42 // Base64 encode using OpenSSL EVP
43 int expected_len = 4 * ((SHA_DIGEST_LENGTH + 2) / 3);
44 std::string base64_key(static_cast<size_t>(expected_len), '\0');
45
46 int encoded_len = EVP_EncodeBlock(
47 reinterpret_cast<unsigned char*>(&base64_key[0]),
48 hash,
49 SHA_DIGEST_LENGTH
50 );
51
52 base64_key.resize(static_cast<size_t>(encoded_len));
53 return base64_key;
54 }
55};
56
57} // namespace websocket
58} // namespace http
Utility class for WebSocket handshakes.
Definition WebSocket.hpp:14
static bool is_valid_client_key(std::string_view key)
Checks that a Sec-WebSocket-Key is the base64 encoding of 16 bytes (RFC 6455 section 4....
Definition WebSocket.hpp:20
static std::string generate_accept_key(const std::string &client_key)
Generates the Sec-WebSocket-Accept key for the WebSocket handshake.
Definition WebSocket.hpp:35
Definition Task.hpp:10
Definition legacy_namespaces.hpp:27