Excepted:我想使用我的AWS CloudFront URL获得签名的URL。
我做了什么:我创建了一个AWS CloudFront实例并启用了Restrict Viewer Access功能,Trusted Signers是Self。
下面是我要签名的php代码
function getSignedURL()
{
$resource = 'http://d2qui8qg6d31zk.cloudfront.net/richardcuicks3sample/140-140.bmp';
$timeout = 300;
//This comes from key pair you generated for cloudfront
$keyPairId = "YOUR_CLOUDFRONT_KEY_PAIR_ID";
$expires = time() + $timeout; //Time out in seconds
$json = '{"Statement":[{"Resource":"'.$resource.'","Condition":{"DateLessThan":{"AWS:EpochTime":'.$expires.'}}}]}';
//Read Cloudfront Private Key Pair
$fp=fopen("private_key.pem","r");
$priv_key=fread($fp,8192);
fclose($fp);
//Create the private key
$key = openssl_get_privatekey($priv_key);
if(!$key)
{
echo "<p>Failed to load private key!</p>";
return;
}
//Sign the policy with the private key
if(!openssl_sign($json, $signed_policy, $key, OPENSSL_ALGO_SHA1))
{
echo '<p>Failed to sign policy: '.openssl_error_string().'</p>';
return;
}
//Create url safe signed policy
$base64_signed_policy = base64_encode($signed_policy);
$signature = str_replace(array('+','=','/'), array('-','_','~'), $base64_signed_policy);
//Construct the URL
$url = $resource.'?Expires='.$expires.'&Signature='.$signature.'&Key-Pair-Id='.$keyPairId;
return $url;
}
对于$keyPairId
和private_key.pem
,我登录了我的root帐户,并在安全凭据-> CloudFront密钥对部分中生成了这两个变量。
如果直接在浏览器上访问http://d2qui8qg6d31zk.cloudfront.net/richardcuicks3sample/140-140.bmp
。它将响应,如
<Error>
<Code>MissingKey</Code>
<Message>
Missing Key-Pair-Id query parameter or cookie value
</Message>
</Error>
运行函数后,我得到了一个长签名的网址,在chrome浏览器中解析该网址,它会像这样响应
<Error>
<Code>InvalidKey</Code>
<Message>Unknown Key</Message>
</Error>
问题:我已经在AWS文档和Google上搜索了很多时间,有人可以告诉我为什么会这样或者我错过了什么吗?预先感谢!
$ priv_key = fread($ fp,8192);
据我所知,您生成了密钥。如果是这样,则好像您正在设置不支持的密钥大小。
感谢@imperalix回答这个问题。
我已经解决了这个问题,
受此site的启发,我发现使用了错误的CloudFront URL进行签名。
之前:http://d2qui8qg6d31zk.cloudfront.net/richardcuicks3sample/140-140.bmp
之后:http://d2qui8qg6d31zk.cloudfront.net/140-140.bmp
因为我为richardcuicks3sample存储桶创建了CloudFront分发,所以不需要在URL中包含此存储桶名称。更改网址后,签名的网址可以正常工作。
我也有这个问题。我的问题是我在错误的位置上传了公钥。对于签名的URL,您必须使用根凭证上载公钥,然后单击右上角>我的安全凭证> CloudFront密钥对中的帐户名。请勿在CloudFront控制台中使用“公钥”,因为这是用于字段级加密的。