Samchon Framework for CPP  1.0.0
WebSocketUtil.hpp
1 #pragma once
2 #include <samchon/API.hpp>
3 
4 #include <string>
5 #include <random>
6 #include <boost/uuid/sha1.hpp>
7 
8 #include <samchon/ByteArray.hpp>
9 #include <samchon/library/Base64.hpp>
10 #include <samchon/library/Date.hpp>
11 
12 namespace samchon
13 {
14 namespace protocol
15 {
16  class WebSocketUtil
17  {
18  public:
19  enum OpCode : unsigned char
20  {
21  TEXT = 129,
22  BINARY = 130,
23  DISCONNECT = 136
24  };
25 
26  enum SizeCode : unsigned char
27  {
28  TWO_BYTES = 126,
29  EIGHT_BYTES = 127
30  };
31 
32  static const unsigned char MASK = 128;
33 
34  static auto GUID() -> std::string
35  {
36  return "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
37  };
38 
39  static auto generate_base64_certification_key() -> std::string
40  {
41  static std::uniform_int_distribution<unsigned short> distribution(0, 255);
42  static std::random_device device;
43 
44  std::string certification_key(16, NULL);
45  for (size_t i = 0; i < certification_key.size(); i++)
46  certification_key[i] = (unsigned char)distribution(device);
47 
48  ByteArray byte_array;
49  byte_array.assign(certification_key.begin(), certification_key.end());
50 
51  return library::Base64::encode(byte_array);
52  };
53 
54  static auto encode_certification_key(const std::string &base64) -> std::string
55  {
56  std::string acceptKey = base64 + GUID();
57 
58  boost::uuids::detail::sha1 hash;
59  hash.process_bytes(acceptKey.c_str(), acceptKey.size());
60 
61  ByteArray bytes;
62  unsigned int digest[5];
63  hash.get_digest(digest);
64 
65  for (size_t index = 0; index < 5; index++)
66  bytes.writeReversely(digest[index]); //ENDIAN REVERSING
67 
68  return library::Base64::encode(bytes);
69  };
70  };
71 };
72 };
static auto encode(const Container &byte_array) -> std::string
Encode from binary data to base64-string.
Definition: Base64.hpp:37