使用 PHP 创建 AWS 签名 [英] AWS Signature creation using PHP

查看:14
本文介绍了使用 PHP 创建 AWS 签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 AWS API 在 AWS CloudFormation 中创建堆栈,但他们返回错误消息我们计算的签名与您提供的签名不匹配"

I am trying to use AWS API to create a stack in AWS CloudFormation, but they return error saying "signature we calculated does not match the signature you provided"

Flowing 是我用来生成签名的代码

Fllowing is the code that I am using to generate the siganture

$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 => $value) {
    $param = str_replace("%7E", "~", rawurlencode($param));
    $value = str_replace("%7E", "~", rawurlencode($value));
    $canonicalized_query[] = $param . "=" . $value;
}
$canonicalized_query = implode("&", $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
&StackName=MyStack
&Version=2010-05-15
&SignatureVersion=2
&Timestamp=2012-09-05T06:32:19Z
&AWSAccessKeyId=[AccessKeyId]
&Signature=[Signature]
&SignatureMethod=HmacSHA256'

推荐答案

我确认了 Frederick 的回答.在对数组进行散列之前,您必须对其进行 ksort.

I confirmed Frederick's answer. You must ksort the array before hashing it.

这篇关于使用 PHP 创建 AWS 签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆