title: C++ Base64 of Sha1 - WebSocket Handshake
body: <p>i am currently trying to get a C++ Server running which can communicate with a WebSocket. The HandShake consists of a couple of steps and I have no success with the last one.</p>
  <p>The first Step is to generate a SHA1 encoded string and I successfully obtained the right hex string. (Example <a href="http://en.wikipedia.org/wiki/WebSocket" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/WebSocket</a> &amp; <a href="https://www.rfc-editor.org/rfc/rfc6455" rel="nofollow noreferrer">https://www.rfc-editor.org/rfc/rfc6455</a>).</p>
  <p>My output is in both cases the same as stated in the documentation:</p>
  <pre><code>Wikipedia: 1d 29 ab 73 4b 0c 95 85 24 00 69 a6 e4 e3 e9 1b 61 da 19 69
  My Server: 1d 29 ab 73 4b 0c 95 85 24 00 69 a6 e4 e3 e9 1b 61 da 19 69
  
  IETF Docu: b3 7a 4f 2c c0 62 4f 16 90 f6 46 06 cf 38 59 45 b2 be c4 ea
  My Server: b3 7a 4f 2c c0 62 4f 16 90 f6 46 06 cf 38 59 45 b2 be c4 ea
  </code></pre>
  <p>So this is right. When i now do the Base64 encoding i come to the following results:</p>
  <pre><code>Wikipedia: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
  My Server: MWQyOWFiNzM0YjBjOTU4NTI0MDA2OWE2ZTRlM2U5MWI2MWRhMTk2OQ==
  
  IETF Docu: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
  My Server: YjM3YTRmMmNjMDYyNGYxNjkwZjY0NjA2Y2YzODU5NDViMmJlYzRlYQ==
  </code></pre>
  <p>And this a completely different. I confirmed that my Base64 algorithm works wtih certain online converters and they all produced the output my server did. So the problem is the input format. I found a forum entry in a javascript forum where one had the same problem and the answer was that , instead of passing the 40 character hex string, we should pass the 20 character binary representation.</p>
  <p>I know that openssl SHA1 returns a binary representation but i can't use the library for certain reasons. The SHA1 library i use, puts the encoded output in an int array. The output looks like this (IETF example):</p>
  <pre><code>result[0] = 3011137324
  result[1] = 3227668246
  result[2] = 2432058886
  result[3] = 3476576581
  result[4] = 2998846698
  </code></pre>
  <p>I convert this than to hex like this:</p>
  <pre><code>std::ostringstream oss;
  oss &lt;&lt; std::setfill('0');
              for (int i = 0; i &lt; 5; ++i) {
                      oss &lt;&lt; std::setw(8) &lt;&lt; std::hex &lt;&lt; result[i];
              }
  </code></pre>
  <p>Now the big question. How can i convert my hex string to binary?</p>
  <p>Thanks a lot in advance .
  Markus</p>
  <p><strong>EDIT</strong></p>
  <p>If someone is interested in the code:
  <a href="https://github.com/MarkusPfundstein/C---Websocket-Server" rel="nofollow noreferrer">https://github.com/MarkusPfundstein/C---Websocket-Server</a></p>