• Модуль: clouds
  • Путь к файлу: ~/bitrix/modules/clouds/classes/general/storage_service_s3.php
  • Класс: CCloudStorageService_S3
  • Вызов: CCloudStorageService_S3::SignRequest
function SignRequest($arSettings, $RequestMethod, $bucket, $RequestURI, $ContentType, $additional_headers, $params = "", $content = "")
{
	if (is_resource($content))
	{
		$streamPosition = ftell($content);
		$hashResource = hash_init("sha256");
		hash_update_stream($hashResource, $content);
		$HashedPayload = hash_final($hashResource);
		fseek($content, $streamPosition);
	}
	else
	{
		$HashedPayload = hash("sha256", $content, false);
	}
	$additional_headers["x-amz-content-sha256"] = $HashedPayload;

	$Time = time();
	$RequestDate = gmdate('Ymd', $Time);
	$RequestTime = gmdate('Ymd', $Time).'T'.gmdate('His', $Time).'Z';
	$additional_headers["x-amz-date"] = $RequestTime;

	do
	{
		$CanonicalizedResource = $RequestURI <> ''? str_replace('%2F', '/', $RequestURI): '/';
	}
	while (strpos($CanonicalizedResource, '%2F') !== false);

	$CanonicalQuery = explode("&", ltrim($params, "?"));
	sort($CanonicalQuery);
	$CanonicalQueryString = str_replace('%7E', '~', implode("&", $CanonicalQuery));

	$CanonicalHeaders = /*.(array[string]string).*/ array();
	foreach($additional_headers as $key => $value)
	{
		$key = mb_strtolower($key);
		if (isset($CanonicalHeaders[$key]))
			$CanonicalHeaders[$key] .= ",";
		else
			$CanonicalHeaders[$key] = $key.":";
		$CanonicalHeaders[$key] .= trim($value, " tnr");
	}
	ksort($CanonicalHeaders);
	$CanonicalHeadersString = implode("n", $CanonicalHeaders);
	$SignedHeaders = implode(";", array_keys($CanonicalHeaders));

	$CanonicalRequest = "";
	$CanonicalRequest .= $RequestMethod."n";
	$CanonicalRequest .= $CanonicalizedResource."n";
	$CanonicalRequest .= $CanonicalQueryString."n";
	$CanonicalRequest .= $CanonicalHeadersString."nn";
	$CanonicalRequest .= $SignedHeaders."n";
	$CanonicalRequest .= $HashedPayload;

	$Algorithm = "AWS4-HMAC-SHA256";
	$Region = $this->location? $this->location: 'us-east-1';
	$Service = "s3";
	$Scope = $RequestDate."/".$Region."/".$Service."/aws4_request";

	$StringToSign = "";
	$StringToSign .= $Algorithm."n";
	$StringToSign .= $RequestTime."n";
	$StringToSign .= $Scope."n";
	$StringToSign .= hash("sha256", $CanonicalRequest, false);

	$kSecret  = $arSettings["SECRET_KEY"];
	$kDate    = hash_hmac("sha256", $RequestDate, "AWS4".$kSecret, true);
	$kRegion  = hash_hmac("sha256", $Region, $kDate, true);
	$kService = hash_hmac("sha256", $Service, $kRegion, true);
	$kSigning = hash_hmac("sha256", "aws4_request", $kService, true);

	$Signature = hash_hmac("sha256", $StringToSign, $kSigning, false);

	$Authorization = "$Algorithm Credential=$arSettings[ACCESS_KEY]/$Scope,SignedHeaders=$SignedHeaders,Signature=$Signature";

	return array(
		"Date" => $RequestTime,
		"Authorization" => $Authorization,
		"x-amz-date" => $RequestTime,
		"x-amz-content-sha256" => $HashedPayload,
	);
}