title: AWS Signature creation using PHP
body: <p>I am trying to use AWS API to create a stack in AWS CloudFormation, but they return error saying "<strong>signature we calculated does not match the signature you provided</strong>"</p>
  
  <p>Fllowing is the code that I am using to generate the siganture</p>
  
  <pre><code>$private_key = "xxxxxxxxxxxxx";
  $params = array();
  $method = "POST";
  $host = "cloudformation.eu-west-1.amazonaws.com";
  $uri = "/onca/xml";
  
  // additional parameters
  $params["Service"] = "AWSCloudFormation";
  $params["Operation"] = "DeleteStack";
  $params["AWSAccessKeyId"] = "xxxxxxxxxxxxxx";
  // GMT timestamp
  $params["Timestamp"] = gmdate("Y-m-d\TH:i:s\Z");
  // API version
  $params["Version"] = "2010-05-15";
  
  // sort the parameters
  // create the canonicalized query
  $canonicalized_query = array();
  foreach ($params as $param =&gt; $value) {
      $param = str_replace("%7E", "~", rawurlencode($param));
      $value = str_replace("%7E", "~", rawurlencode($value));
      $canonicalized_query[] = $param . "=" . $value;
  }
  $canonicalized_query = implode("&amp;", $canonicalized_query);
  
  // create the string to sign
  $string_to_sign = $method . "\n" . $host . "\n" . $uri . "\n" . $canonicalized_query;
  
  // calculate HMAC with SHA256 and base64-encoding
  $signature = base64_encode(hash_hmac("sha256", $string_to_sign, $private_key, True));
  
  // encode the signature for the request
  $signature = str_replace("%7E", "~", rawurlencode($signature));
  
  the url I am using is 
  
  'https://cloudformation.us-east-1.amazonaws.com/
  ?Action=DeleteStack
  &amp;StackName=MyStack
  &amp;Version=2010-05-15
  &amp;SignatureVersion=2
  &amp;Timestamp=2012-09-05T06:32:19Z
  &amp;AWSAccessKeyId=[AccessKeyId]
  &amp;Signature=[Signature]
  &amp;SignatureMethod=HmacSHA256'
  </code></pre>