title: HMAC SHA256 in C++ (DynamoDB)
body: <p>I'm trying to connect to DynamoDB through the REST Web API and it requires me to generate a signature using HMAC-SHA256. I've got SHA-256 working, but I cant seem to get HMAC working, here is the C++ code (using OpenSSL)</p>
  
  <pre><code>string hmac(string key, string msg)
  {
      unsigned char hash[32];
  
      HMAC_CTX hmac;
      HMAC_CTX_init(&amp;hmac);
      HMAC_Init_ex(&amp;hmac, &amp;key[0], key.length(), EVP_sha256(), NULL);
      HMAC_Update(&amp;hmac, (unsigned char*) &amp;msg[0], msg.length());
      unsigned int len = 32;
      HMAC_Final(&amp;hmac, hash, &amp;len);
      HMAC_CTX_cleanup(&amp;hmac);
  
      stringstream ss;
      for (int i = 0; i &lt; len; i++)
      {   
          ss &lt;&lt; hex  &lt;&lt;  ( unsigned int )hash[i];
      }
  
      return ss.str();
  }
  </code></pre>
  
  <p>Here is the call to hmac</p>
  
  <pre><code>    /*********************************************CALCULATE SIGNATURE****************************************************************/
  
  string AWS4 = "AWS4" + secretKey;
  
  string Kdate = hmac(AWS4.data(), dateStamp);
  string Kregion = hmac(Kdate.data(), region);
  string Kservice = hmac(Kregion.data(), service);
  string signingkey = hmac(Kservice.data(), "aws4_request");
  
  string signature = hmac(signingkey.data(), stringToSign);
  
  string authoritzationHeader = algorithm + " Credential=" + accessKey + "/" + credential_scope + ", SignedHeaders=" + signedHeaders + ", Signature=" + signature;
  </code></pre>
  
  <p>This is the Python code I'm basing it off:</p>
  
  <pre><code>def sign(key, msg):
      return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()
  
  def getSignatureKey(key, date_stamp, regionName, serviceName):
      kDate    = sign(('AWS4' + key).encode('utf-8'), date_stamp)
      kRegion  = sign(kDate, regionName)
      kService = sign(kRegion, serviceName)
      kSigning = sign(kService, 'aws4_request')
  
      print 'Kdate: ' + kDate
      print 'Kregion: ' + kRegion 
      print 'Kservice: ' + kService
  
      return kSigning
  </code></pre>
  
  <p>Given the same values they produce a different result. Can anyone help me as to why this is? Thanks.</p>