search
HomeBackend DevelopmentPHP TutorialPHP generates the relevant content of the request signature required by Tencent Cloud COS interface

This article mainly introduces the request signature required to create a COS interface using PHP. It is compared with the examples given in the official documents to verify the correctness of the algorithm. Friends in need can refer to it

What is COS and request signature

COS is the abbreviation and abbreviation of Tencent Cloud Object Storage. The request signature is created by a specific algorithm and needs to be provided by a third party on demand when calling COS related interfaces. A set of string information that will uniquely identify the current third-party identity and provide identification of both communicating parties. Only valid signed COS will provide services

Goal

Use PHP to create the request signature required for the COS interface, compare it with the example given in the official document, and verify the correctness of the algorithm

Understand the request signature

Come first Look at the request signature given in an official document

q-sign-algorithm=sha1&q-ak=[SecretID]&q-sign-time=[SignTime]&q-key-time=[KeyTime ]&q-header-list=[SignedHeaderList]&q-url-param-list=[SignedParameterList]&q-signature=[Signature]

Request signature feature summary

  • is a key-value pair format of a string

  • key=value, the key is a fixed value

  • There are 7 pairs of keys in total =value

  • sha1 is also a parameter, but as of the official release, only sha1 is supported, so you can directly assign values ​​to

  • SignedHeaderList, SignedParameterList, and Signature. value needs to be generated through an algorithm

For detailed description of key-value pairs, please refer to the official documentation.

Breakdown one by one

Requesting a signature requires a total of 7 values. Let’s explain one by one below and break each one

q-sign-algorithm

Signature algorithm, official Currently only sha1 is supported, so just give the value directly

q-ak

The account ID, which is the user's SecretId, can be obtained on the console Cloud API Key page

q-sign-time

The valid start and end time of the current signature, Unix timestamp format, English half-width semicolon; separated, format such as 1480932292;1481012298

q-key-time

Same as q-sign-time value

q-header-list

Personal understanding, it consists of HTTP request headers, take all or part of the request headers, and change the request in the form of key:value The key part of the item is taken out, converted to lowercase, multiple keys are sorted according to the dictionary, and connected with the characters ; to finally form a string

For example, the original request header has two:

Host: bucket1-1254000000.cos.ap-beijing.myqcloud.com
Content-Type:image/jpeg

key is Host and Content-Type. After operation, content-type;host# is output.

##q-url-param-list

Personal understanding, it consists of HTTP request parameters, take all or part of the request parameters, take out the key part of the request parameter in the form of key=value, and convert it to lowercase. Multiple keys are sorted by dictionary, connected by characters ;, and finally formed into a string

For example, the original HTTP request is:

GET /?prefix=abc&max-keys=20

key is prefix and max-keys. After operation, max-keys;prefix is ​​output. If the request has no parameters such as put and post, it will be empty.

q-signature

Calculate the signature based on the HTTP content. The algorithm is provided by COS. Just give the value as required

Official examples and reference results

Before starting to write logic, take a look at the official examples. The reference value, as well as the calculated result, in order to compare the result with the logic developed by yourself

HTTP original request can also be understood as the HTTP request before calculating the signature or when no signature is required:

PUT /testfile2 HTTP/1.1

Host: bucket1-1254000000.cos.ap-beijing.myqcloud.com
x-cos-content-sha1: 7b502c3a1f48c8609ae212cdfb639dee39673f5e
x-cos-storage -class: standard

Hello world

The HTTP request you should get after calculating the signature:

PUT /testfile2 HTTP/1.1
Host: bucket1-1254000000.cos.ap-beijing.myqcloud.com
x-cos-content-sha1: 7b502c3a1f48c8609ae212cdfb639dee39673f5e
x-cos-storage -class: standard
Authorization: q-sign-algorithm=sha1&q-ak=AKIDQjz3ltompVjBni5LitkWHFlFpwkn9U5q&> q-sign-time=1417773892;1417853898&q-key-time=1417773892;1417853898&q-header-list =host;x-cos-content -sha1;x-cos-storage-class&q-url-param-list=&q-signature=14e6ebd7955b0c6da532151bf97045e2c5a64e10

Hello world

Conclusion: If the algorithm can get the one after Authorization The string string is correct

Preparation work

Let’s take a look at the (officially provided) user information and HTTP information:

  • ##SecretId: AKIDQjz3ltompVjBni5LitkWHFlFpwkn9U5q

  • SecretKey: BQYIM75p8x0iWVFSIgqEKwFprpRSVHlz

  • Signature valid start time: 1417773892

  • Signature valid stop time: 1417853898

  • HTTP original request header: According to the example in the previous section, it is not difficult to get that the HTTP original request has three contents: Host, x-cos-content-sha1 and x-cos-storage-class

  • HTTP request parameters: Is it a PUT request, no? Parameters

Calculate signature

Put all parameters in preparation Bringing in the request signature rules, it is not difficult to get the results, as shown in the following table:


Key (key) Value(value)Remark##q-sign-algorithmq-akq-sign-time q- key-timeq-header-listq-url-param-listq-signature

But where did q-signature come from?

As mentioned just now, q-signature also needs to be calculated by a specific algorithm. The following explains how to calculate it

Calculate the request signature

Look at the code first :

/**
 * 计算签名
 * secretId、secretKey 为必需参数,qSignStart、qSignEnd为调试需要,测试通过后应取消,改为方法内自动创建
 */
function get_authorization( $secretId, $secretKey, $qSignStart, $qSignEnd, $fileUri, $headers ){
 /* 
 * 计算COS签名
 * 2018-05-17
 * author:cinlap <cash216@163>
 * ref:https://cloud.tencent.com/document/product/436/7778
 */

 $qSignTime = "$qSignStart;$qSignEnd"; //unix_timestamp;unix_timestamp
 $qKeyTime = $qSignTime;

 $header_list = get_q_header_list($headers);
 //如果 Uri 中带有 ?的请求参数,该处应为数组排序后的字符串组合
 $url_param_list = &#39;&#39;;

 //compute signature
 $httpMethod = &#39;put&#39;;
 $httpUri = $fileUri;

 //与 q-url-param-list 相同
 $httpParameters = $url_param_list;

 //将自定义请求头分解为 & 连接的字符串
 $headerString = get_http_header_string( $headers );

 // 计算签名中的 signature 部分
 $signTime = $qSignTime;
 $signKey = hash_hmac(&#39;sha1&#39;, $signTime, $secretKey);
 $httpString = "$httpMethod\n$httpUri\n$httpParameters\n$headerString\n";
 $sha1edHttpString = sha1($httpString);
 $stringToSign = "sha1\n$signTime\n$sha1edHttpString\n";
 $signature = hash_hmac(&#39;sha1&#39;, $stringToSign, $signKey);
 //组合结果
 $authorization = "q-sign-algorithm=sha1&q-ak=$secretId&q-sign-time=$qSignTime&q-key-time=$qKeyTime&q-header-list=$header_list&q-url-param-list=$url_param_list&q-signature=$signature";
 return $authorization;
}

For testing, this method should have more parameters than needed. The first six parameters have been given and come from the user, so directly Assign a value to get the following string:

$authorization = "q-sign-algorithm=sha1&q-ak=$secretId&q-sign-time=$qSignTime&q-key-time=$qKeyTime...

$header_list This value must comply with the q-header-list rules and therefore needs to be calculated. The logic is as described above, which is to extract keys from the established request items to form an orderly String, the code is as follows:

/**
 * 按COS要求对header_list内容进行转换
 * 提取所有key
 * 字典排序
 * key转换为小写
 * 多对key=value之间用连接符连接
 * 
 */
function get_q_header_list($headers){
 if(!is_array($headers)){
  return false;
 }

 try{
  $tmpArray = array();
  foreach( $headers as $key=>$value){
   array_push($tmpArray, strtolower($key));
  }
  sort($tmpArray);
  return implode(&#39;;&#39;, $tmpArray);
 }
 catch(Exception $error){
  return false;
 }
}

$url-param-list As mentioned above, this value is an HTTP request parameter. There is no ? parameter for the PUT method, naturally. The value is empty, so the code is "lazy" and directly gives the empty string.

Signature calculation and things to be careful about

The official has given a complete Algorithm, PHP and even written code, I should be very happy (but! I was dizzy after reading the official document, so I will explain it later), first take a look at the "format" of signature:

SignKey = HMAC-SHA1(SecretKey,"[q-key-time]")
HttpString = [HttpMethod]\n[HttpURI]\n[HttpParameters]\n[HttpHeaders]\n
StringToSign = [q-sign-algorithm]\n[q-sign-time]\nSHA1-HASH(HttpString)\n
Signature = HMAC-SHA1(SignKey,StringToSign)

again Take a look at the complete algorithm of Signature:

$signTime = $qSignTime;
$signKey = hash_hmac('sha1', $signTime, $secretKey);
$httpString = "$httpMethod \n$httpUri\n$httpParameters\n$headerString\n";
$sha1edHttpString = sha1($httpString);
$stringToSign = "sha1\n$signTime\n$sha1edHttpString\n";
$signature = hash_hmac('sha1', $stringToSign, $signKey);

$signTime: very simple, a string consisting of start and end time, just use it from above
$ signKey: HMAC-SHA1 algorithm can be calculated directly
$httpString: The four parts need to be said separately
1, $httpMethod: HTTP request method, lowercase, such as put, get
2. $httpUri: The URI part of the HTTP request, starting from the "/" virtual root, such as /testfile means creating a file called testfile in the root directory of the bucket, /image/face1.jpg means creating a file called testfile in the root directory/image directory. Create a file called face1.jpg. As for whether it is an image file or not, it doesn’t matter
3, $httpParameters: This is the first place to be careful. It consists of HTTP original request parameters, that is, the part after ? in the request URI. This example calls the PUT Object interface, so it is empty. If it is not empty, you need to convert the key and value of each item of the request parameter to lowercase. Multiple pairs of key=value are sorted by dictionary and connected with &
4. $headerString: This is the second place to be careful. , consisting of HTTP original request headers. According to the request headers, select all or part of the request headers, convert the keys of each item to lowercase, convert the values ​​to URLEncode, change the format of each item to key=value, and then proceed according to the key. Dictionary sorting, and finally use the connector & to form a string. This is the logic I compiled. The code is as follows:

/**
 * 按COS要求从数组中获取 Signature 中 [HttpString] 内容
 * 标准格式 key=value&key=value&... 
 * 数组元素按键字典排序 * 
 * key转换为小写
 * value进行UrlEncode转换
 * 转换为key=value格式
 * 多对key=value之间用连接符连接
 * 
 */
function get_http_header_string($headers){
 if(!is_array($headers)){
  return false;
 }

 try{
  $tmpArray = array();
  foreach($headers as $key => $value){
   $tmpKey = strtolower($key);
   $tmpArray[$tmpKey] = urlencode($value);
  }
  ksort($tmpArray);
  $headerArray = array();
  foreach( $tmpArray as $key => $value){
   array_push($headerArray, "$key=$value");
  }
  return implode(&#39;&&#39;, $headerArray);
 }
 catch(Exception $error){
  return false;
 }
}

Why should you be careful?

HTTP original request headers and request parameters are used in four places, namely q-header-list in the request signature and HttpHeaders in the Signature - both use the HTTP original request header; request signature q-url-param-list in Signature and HttpParameters in Signature - both use HTTP request parameters. Be sure to ensure that the number of HTTP request headers and request parameters selected is consistent with the object

  • : the number and members of the HTTP request headers generated by q-header-list must be the same as those used to generate HttpHeaders. The number and members of the HTTP request parameters generated by q-url-param-list must be the same as those generated by HttpParameters.

  • is different: q-header-list and q-url-param-list only take In the key part, HttpHeaders and HttpParameters take the key and value parts

Output results and verification

At this point, there are 7 values ​​in the request signature Some of them come from user information, and some need to be calculated. All the calculation methods and personal understanding of why they are calculated are also given above. Finally, you only need to output according to the official requirements. take a look

sha1 Currently only supported sha1 signature algorithm
AKIDQjz3ltompVjBni5LitkWHFlFpwkn9U5q SecretId field
1417773892;1417853898 2014/12/5 18:04:52 to 2014/12/6 16:18:18
1417773892;1417853898 2014/12/5 18:04:52 to 2014/12/6 16:18:18
host;x-cos-content-sha1;x-cos-storage-class lexicographically sorted list of HTTP header keys

HTTP parameter list is empty
14e6ebd7955b0c6da532151bf97045e2c5a64e10 Calculated by code

The above is the detailed content of PHP generates the relevant content of the request signature required by Tencent Cloud COS interface. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP: The Foundation of Many WebsitesPHP: The Foundation of Many WebsitesApr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

Beyond the Hype: Assessing PHP's Role TodayBeyond the Hype: Assessing PHP's Role TodayApr 12, 2025 am 12:17 AM

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

What are Weak References in PHP and when are they useful?What are Weak References in PHP and when are they useful?Apr 12, 2025 am 12:13 AM

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

Explain the __invoke magic method in PHP.Explain the __invoke magic method in PHP.Apr 12, 2025 am 12:07 AM

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.