title: Signature Version 4 Signing Process in PHP to access API Gateway endpoint
body: <p>I am trying to create Authorized Signature to access IAM secured API gateway endpoint.</p>
  
  <pre><code>$alg = "SHA256";
  $CanonicalRequest = "GET\n/dev/pets\n\nhost:3r4fgts8e5.execute-api.ap-northeast-1.amazonaws.com\nx-amz-date:".$dd."\n\nhost;x-amz-date\ne3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
  
  $CR =  str_replace("\n", "", $CanonicalRequest);
              $CR = str_replace("\r", "", $CR);
              $CR = strtolower($CR);
  
  
  
  
  $StringToSign  = "AWS4-HMAC-SHA256\n".$dd."\n".$date-&gt;format( 'Ymd' )."/ap-northeast-1/execute-api/aws4_request\n".hash( $alg, $CR )."";
  
  
  
  
  
  // 1) HMACs
  $kSecret = 'AWS4' . $secret_key;
  $kDate = hash_hmac( $alg, $date-&gt;format( 'Ymd' ), $kSecret, true );     
  $kRegion = hash_hmac( $alg, $region, $kDate, true );
  $kService = hash_hmac( $alg, $service, $kRegion, true );
  $kSigning = hash_hmac( $alg, 'aws4_request', $kService, true );     
  $signature = hash_hmac( $alg, $StringToSign, $kSigning );       
  
  $authorization = array(
      'Credential=' . $access_key . '/' . implode( '/', $scope ),
      'SignedHeaders=' . implode( ';', array_keys( $can_headers ) ),
      'Signature=' . $signature,
  );
  $authorization = $request['algorithm'] . ' ' . implode( ',', $authorization );
  $request['Authorization'] = $authorization;
  </code></pre>
  
  <p><strong><em>But I am getting "The request signature we calculated does not match the signature you provided" error</em></strong></p>
  
  <blockquote>
    <p>"message": "The request signature we calculated does not match the
    signature you provided. Check your AWS Secret Access Key and signing
    method. Consult the service documentation for details.\n\nThe
    Canonical String for this request should have
    been\n'GET\n/dev/pets\n\nhost:3r4fgts8e5.execute-api.ap-northeast-1.amazonaws.com\nx-amz-date:20161002T231640Z\n\nhost;x-amz-date\ne3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'\n\nThe
    String-to-Sign should have
    been\n'AWS4-HMAC-SHA256\n20161002T231640Z\n20161002/ap-northeast-1/execute-api/aws4_request\n0b8c12e0a5f21137c5739a9d26056dfb081218631a9adcf37db1d2e09a014c4e'\n"</p>
  </blockquote>
  
  <p>My String-to-sign string is</p>
  
  <pre><code>"AWS4-HMAC-SHA256
  20161002T231640Z
  20161002/ap-northeast-1/execute-api/aws4_request
  fb4f7ebdcb405bceed598ecc097267b929eeb3f8f075b1b7a776f53c8c8c6168"
  </code></pre>
  
  <p>which is totally different from what AWS expected in signature.</p>