title: HMAC-SHA-256 in PHP
body: <p>I have to build an authorization hash from this string:</p>
  <pre><code>kki98hkl-u5d0-w96i-62dp-xpmr6xlvfnjz:20151110171858:b2c13532-3416-47d9-8592-a541c208f755:hKSeRD98BHngrNa51Q2IgAXtoZ8oYebgY4vQHEYjlmzN9KSbAVTRvQkUPsjOGu4F
  </code></pre>
  <p>This secret is used for a HMAC hash function:</p>
  <pre><code>LRH9CAkNs-zoU3hxHbrtY0CUUcmqzibPeN7x6-vwNWQ=
  </code></pre>
  <p>The authorization hash I have to generate is this:</p>
  <pre><code>P-WgZ8CqV51aI-3TncZj5CpSZh98PjZTYxrvxkmQYmI=
  </code></pre>
  <p>There are some things to take care of:</p>
  <ol>
  <li>The signature have to be built with HMAC-SHA-256 as specified in <a href="https://www.rfc-editor.org/rfc/rfc2104" rel="nofollow noreferrer">RFC 2104</a>.</li>
  <li>The signature have to be encoded with Base64 URL-compatible as specified in <a href="https://www.rfc-editor.org/rfc/rfc4648" rel="nofollow noreferrer">RFC 4648 Section 5</a> (Safe alphabet).</li>
  </ol>
  <p>There is also some pseudo-code given for the generation:</p>
  <pre><code>Signatur(Request) = new String(encodeBase64URLCompatible(HMAC-SHA-256(getBytes(Z, &quot;UTF-8&quot;), decodeBase64URLCompatible(getBytes(S, &quot;UTF-8&quot;)))), &quot;UTF-8&quot;)
  </code></pre>
  <p>I tried various things in PHP but have not found the correct algorithm yet. This is the code I have now:</p>
  <pre><code>if(!function_exists('base64url_encode')){
      function base64url_encode($data) {
          $data = str_replace(array('+', '/'), array('-', '_'), base64_encode($data));
          return $data;
      }
  }
  
  $str = &quot;kki98hkl-u5d0-w96i-62dp-xpmr6xlvfnjz:20151110171858:b2c13532-3416-47d9-8592-a541c208f755:hKSeRD98BHngrNa51Q2IgAXtoZ8oYebgY4vQHEYjlmzN9KSbAVTRvQkUPsjOGu4F&quot;;
  $sec = &quot;LRH9CAkNs-zoU3hxHbrtY0CUUcmqzibPeN7x6-vwNWQ=&quot;;
  $signature = mhash(MHASH_SHA256, $str, $sec);
  $signature = base64url_encode($signature);
  
  if($signature != &quot;P-WgZ8CqV51aI-3TncZj5CpSZh98PjZTYxrvxkmQYmI=&quot;)
      echo &quot;wrong: $signature&quot;;
  else
      echo &quot;correct&quot;;
  </code></pre>
  <p>It gives this signature:</p>
  <pre><code>K9lw3V-k5gOedmVwmO5vC7cOn82JSEXsNguozCAOU2c=
  </code></pre>
  <p>As you can see, the length of 44 characters is correct. Please help me with finding the mistake, this simple problem takes me hours yet and there is no solution.</p>