TencentCloud API authenticates every single request, i.e., the request must be signed using the security credentials in the designated steps. Each request has to contain the signature information (Signature) in the common request parameters and be sent in the specified way and format.
The security credential used in this document is a key, which includes a SecretId and a SecretKey. Each user can have up to two pairs of keys.
You can apply for the security credentials through the following steps:
TencentCloud API comes with SDKs for seven commonly used programming languages, including Python, Java, PHP, Go, NodeJS and .NET. In addition, it provides API Explorer which enables online call, signature verification, and SDK code generation. If you have any troubles calculating a signature, consult these resources.
Compatible with the previous HmacSHA1 and HmacSHA256 signature algorithms, the TC3-HMAC-SHA256 signature algorithm is more secure and supports larger requests and JSON format with better performance. We recommend using TC3-HMAC-SHA256 to calculate the signature.
TencentCloud API supports both GET and POST requests. For the GET method, only the Content-Type: application/x-www-form-urlencoded protocol format is supported. For the POST method, two protocol formats, Content-Type: application/json and Content-Type: multipart/form-data, are supported. The JSON format is supported by default for all business APIs, and the multipart format is supported only for specific business APIs. In this case, the API cannot be called in JSON format. See the specific business API documentation for more information. The POST method is recommended, as there is no difference in the results of both the methods, but the GET method only supports request packets up to 32 KB.
The following uses querying the list of CVM instances in the Guangzhou region as an example to describe the steps of signature splicing. We chose this API because:
In the example, we try to choose common parameters and API parameters that are prone to mistakes. When you actually call an API, please use parameters based on the actual conditions. The parameters vary by API. Do not copy the parameters and values in this example.
Assuming that your SecretId and SecretKey are AKID******************************** and ********************************, respectively, if you want to view the status of the instance in the Guangzhou region whose CVM instance name is "unnamed" and have only one data entry returned, then the request may be:
curl -X POST https://cvm.tencentcloudapi.com \
-H "Authorization: TC3-HMAC-SHA256 Credential=AKID********************************/2019-02-25/cvm/tc3_request, SignedHeaders=content-type;host, Signature=a7b8551448762bd123d6f79e81815e31a92013640a6cef36a08ad4b292a4d2f2" \
-H "Content-Type: application/json; charset=utf-8" \
-H "Host: cvm.tencentcloudapi.com" \
-H "X-TC-Action: DescribeInstances" \
-H "X-TC-Timestamp: 1551113065" \
-H "X-TC-Version: 2017-03-12" \
-H "X-TC-Region: ap-guangzhou" \
-d '{"Limit": 1, "Filters": [{"Values": ["unnamed"], "Name": "instance-name"}]}'
The signature calculation process is explained in detail below.
Concatenate the canonical request string (CanonicalRequest) in the following pseudocode format:
CanonicalRequest =
HTTPRequestMethod + '\n' +
CanonicalURI + '\n' +
CanonicalQueryString + '\n' +
CanonicalHeaders + '\n' +
SignedHeaders + '\n' +
HashedRequestPayload
| Field Name | Explanation |
|---|---|
| HTTPRequestMethod | HTTP request method (GET or POST). This example uses POST. |
| CanonicalURI | URI parameter. Slash ("/") is used for API 3.0. |
| CanonicalQueryString | The query string in the URL of the originating HTTP request. This is always an empty string “” for POST requests, and is the string after the question mark (?) for GET requests. For example: Limit=10&Offset=0。 Note: CanonicalQueryString must be URL-encoded, referencing RFC3986, the UTF8 character set. We recommend using the programming language library. All special characters must be encoded and capitalized. |
| CanonicalHeaders | Header information for signature calculation, including at least two headers of host and content-type. Custom headers can be added to participate in the signature process to improve the uniqueness and security of the request. Concatenation rules:
content-type:application/json; charset=utf-8\nhost:cvm.tencentcloudapi.com\n. Note: content-type must match the actually sent content. In some programming languages, a charset value would be added even if it is not specified. In this case, the request sent is different from the one signed, and the sever will return an error indicating that signature verification failed. |
| SignedHeaders | Header information for signature calculation, indicating which headers of the request participate in the signature process (they must each individually correspond to the headers in CanonicalHeaders). Content-type and host are required headers. Concatenation rules:
content-type;host |
| HashedRequestPayload | Hash value of the request payload (i.e., the body, such as {"Limit": 1, "Filters": [{"Values": ["unnamed"], "Name": "instance-name"}]} in this example). The pseudocode for calculation is Lowercase(HexEncode(Hash.SHA256(RequestPayload))) by SHA256 hashing the payload of the HTTP request, performing hexadecimal encoding, and finally converting the encoded string to lowercase letters. For GET requests, RequestPayload is always an empty string. The calculation result in this example is 99d58dfbc6745f6747f36bfca17dee5e6881dc0428a0a36f96199342bc5b4907. |
According to the rules above, the CanonicalRequest string obtained in the example is as follows:
POST
/
content-type:application/json; charset=utf-8
host:cvm.tencentcloudapi.com
content-type;host
99d58dfbc6745f6747f36bfca17dee5e6881dc0428a0a36f96199342bc5b4907
The string to sign is concatenated as follows:
StringToSign =
Algorithm + \n +
RequestTimestamp + \n +
CredentialScope + \n +
HashedCanonicalRequest
| Field Name | Explanation |
|---|---|
| Algorithm | Signature algorithm, which is currently always TC3-HMAC-SHA256. |
| RequestTimestamp | Request timestamp, i.e., the value of the common parameter X-TC-Timestamp in the request header, which is the UNIX timestamp of the current time in seconds, such as 1551113065 in this example. |
| CredentialScope | Scope of the credential in the format of Date/service/tc3_request, including the date, requested service and termination string (tc3_request). Date is a date in UTC time, whose value should match the UTC date converted by the common parameter X-TC-Timestamp; service is the product name, which should match the domain name of the product called. The calculation result in this example is 2019-02-25/cvm/tc3_request. |
| HashedCanonicalRequest | Hash value of the CanonicalRequest string concatenated in the steps above. The pseudocode for calculation is Lowercase(HexEncode(Hash.SHA256(CanonicalRequest))). The calculation result in this example is 2815843035062fffda5fd6f2a44ea8a34818b0dc46f024b8b3786976a3adda7a. |
Note:
- Date has to be calculated from the timestamp "X-TC-Timestamp" and the time zone is UTC+0. If you add the system's local time zone information (such as UTC+8), calls can succeed both day and night but will definitely fail at 00:00. For example, if the timestamp is 1551113065 and the time in UTC+8 is 2019-02-26 00:44:25, the UTC+0 date in the calculated Date value should be 2019-02-25 instead of 2019-02-26.
- Timestamp must be the same as your current system time, and your system time and standard time must be synced; if the difference between Timestamp and your current system time is larger than five minutes, the request will fail. If your system time is out of sync with the standard time for a while, the request will fail and return a signature expiration error.
According to the preceding rules, the string to be signed obtained in the example is as follows:
TC3-HMAC-SHA256
1551113065
2019-02-25/cvm/tc3_request
2815843035062fffda5fd6f2a44ea8a34818b0dc46f024b8b3786976a3adda7a
1) Calculate the derived signature key with the following pseudocode:
SecretKey = "********************************"
SecretDate = HMAC_SHA256("TC3" + SecretKey, Date)
SecretService = HMAC_SHA256(SecretDate, Service)
SecretSigning = HMAC_SHA256(SecretService, "tc3_request")
| Field Name | Explanation |
|---|---|
| SecretKey | The original SecretKey, i.e., ********************************. |
| Date | The Date field information in Credential, such as 2019-02-25 in this example. |
| Service | Value in the Service field in Credential, such as cvm in this example. |
2) Calculate the signature with the following pseudocode:
Signature = HexEncode(HMAC_SHA256(SecretSigning, StringToSign))
The Authorization is concatenated as follows:
Authorization =
Algorithm + ' ' +
'Credential=' + SecretId + '/' + CredentialScope + ', ' +
'SignedHeaders=' + SignedHeaders + ', ' +
'Signature=' + Signature
| Field Name | Explanation |
|---|---|
| Algorithm | Signature algorithm, which is always TC3-HMAC-SHA256. |
| SecretId | The SecretId in the key pair, i.e., AKID********************************. |
| CredentialScope | Credential scope (see above). The calculation result in this example is 2019-02-25/cvm/tc3_request. |
| SignedHeaders | Header information for signature calculation (see above), such as content-type;host in this example. |
| Signature | Signature value. The calculation result in this example is a7b8551448762bd123d6f79e81815e31a92013640a6cef36a08ad4b292a4d2f2. |
According to the rules above, the value obtained in the example is:
TC3-HMAC-SHA256 Credential=AKID********************************/2019-02-25/cvm/tc3_request, SignedHeaders=content-type;host, Signature=a7b8551448762bd123d6f79e81815e31a92013640a6cef36a08ad4b292a4d2f2
The following example shows a finished authorization header:
POST https://cvm.tencentcloudapi.com/
Authorization: TC3-HMAC-SHA256 Credential=AKID********************************/2019-02-25/cvm/tc3_request, SignedHeaders=content-type;host, Signature=a7b8551448762bd123d6f79e81815e31a92013640a6cef36a08ad4b292a4d2f2
Content-Type: application/json; charset=utf-8
Host: cvm.tencentcloudapi.com
X-TC-Action: DescribeInstances
X-TC-Version: 2017-03-12
X-TC-Timestamp: 1551113065
X-TC-Region: ap-guangzhou
{"Limit": 1, "Filters": [{"Values": ["unnamed"], "Name": "instance-name"}]}
When calling API 3.0, you are recommended to use the corresponding Tencent Cloud SDK 3.0 which encapsulates the signature process, enabling you to focus on only the specific APIs provided by the product when developing. See SDK Center for more information. Currently, the following programming languages are supported:
To further explain the signing process, we will use a programming language to implement the process described above. The request domain name, API and parameter values in the sample are used here. This goal of this example is only to provide additional clarification for the signature process, please see the SDK for actual usage.
The final output URL might be: https://cvm.tencentcloudapi.com/?Action=DescribeInstances&InstanceIds.0=ins-09dx96dg&Limit=20&Nonce=11886&Offset=0&Region=ap-guangzhou&SecretId=AKID********************************&Signature=EliP9YW3pW28FpsEdkXt%2F%2BWcGeI%3D&Timestamp=1465185768&Version=2017-03-12.
Note: The key in the example is fictitious, and the timestamp is not the current time of the system, so if this URL is opened in the browser or called using commands such as curl, an authentication error will be returned: Signature expired. In order to get a URL that can work properly, you need to replace the SecretId and SecretKey in the example with your real credentials and use the current time of the system as the Timestamp.
Note: In the example below, even if you use the same programming language, the order of the parameters in the URL may be different for each execution. However, the order does not matter, as long as all the parameters are included in the URL and the signature is calculated correctly.
Note: The following code is only applicable to API 3.0. It cannot be directly used in other signature processes. Even with an older API, signature calculation errors may occur due to the differences in details. Please refer to the corresponding documentation.
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.TreeMap;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
public class TencentCloudAPITC3Demo {
private final static Charset UTF8 = StandardCharsets.UTF_8;
private final static String SECRET_ID = "AKID****";
private final static String SECRET_KEY = "****";
private final static String CT_JSON = "application/json; charset=utf-8";
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-built_in">byte</span>[] hmac256(<span class="hljs-built_in">byte</span>[] <span class="hljs-built_in">key</span>, <span class="hljs-keyword">String</span> msg) <span class="hljs-keyword">throws</span> Exception {
Mac mac = Mac.getInstance(<span class="hljs-string">"HmacSHA256"</span>);
SecretKeySpec secretKeySpec = <span class="hljs-keyword">new</span> SecretKeySpec(<span class="hljs-built_in">key</span>, mac.getAlgorithm());
mac.init(secretKeySpec);
<span class="hljs-keyword">return</span> mac.doFinal(msg.getBytes(UTF8));
}
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">String</span> sha256Hex(<span class="hljs-keyword">String</span> s) <span class="hljs-keyword">throws</span> Exception {
MessageDigest md = MessageDigest.getInstance(<span class="hljs-string">"SHA-256"</span>);
<span class="hljs-built_in">byte</span>[] d = md.digest(s.getBytes(UTF8));
<span class="hljs-keyword">return</span> DatatypeConverter.printHexBinary(d).toLowerCase();
}
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> main(<span class="hljs-keyword">String</span>[] args) <span class="hljs-keyword">throws</span> Exception {
<span class="hljs-keyword">String</span> service = <span class="hljs-string">"cvm"</span>;
<span class="hljs-keyword">String</span> host = <span class="hljs-string">"cvm.tencentcloudapi.com"</span>;
<span class="hljs-keyword">String</span> region = <span class="hljs-string">"ap-guangzhou"</span>;
<span class="hljs-keyword">String</span> action = <span class="hljs-string">"DescribeInstances"</span>;
<span class="hljs-keyword">String</span> version = <span class="hljs-string">"2017-03-12"</span>;
<span class="hljs-keyword">String</span> algorithm = <span class="hljs-string">"TC3-HMAC-SHA256"</span>;
<span class="hljs-keyword">String</span> timestamp = <span class="hljs-string">"1551113065"</span>;
<span class="hljs-comment">//String timestamp = String.valueOf(System.currentTimeMillis() / 1000);</span>
SimpleDateFormat sdf = <span class="hljs-keyword">new</span> SimpleDateFormat(<span class="hljs-string">"yyyy-MM-dd"</span>);
<span class="hljs-comment">// Pay attention to the time zone; otherwise, errors may occur</span>
sdf.setTimeZone(TimeZone.getTimeZone(<span class="hljs-string">"UTC"</span>));
<span class="hljs-keyword">String</span> date = sdf.format(<span class="hljs-keyword">new</span> Date(Long.valueOf(timestamp + <span class="hljs-string">"000"</span>)));
<span class="hljs-comment">// ************* Step 1: Concatenate the CanonicalRequest string *************</span>
<span class="hljs-keyword">String</span> httpRequestMethod = <span class="hljs-string">"POST"</span>;
<span class="hljs-keyword">String</span> canonicalUri = <span class="hljs-string">"/"</span>;
<span class="hljs-keyword">String</span> canonicalQueryString = <span class="hljs-string">""</span>;
<span class="hljs-keyword">String</span> canonicalHeaders = <span class="hljs-string">"content-type:application/json; charset=utf-8\n"</span> + <span class="hljs-string">"host:"</span> + host + <span class="hljs-string">"\n"</span>;
<span class="hljs-keyword">String</span> signedHeaders = <span class="hljs-string">"content-type;host"</span>;
<span class="hljs-keyword">String</span> payload = <span class="hljs-string">"{\"Limit\": 1, \"Filters\": [{\"Values\": [\"unnamed\"], \"Name\": \"instance-name\"}]}"</span>;
<span class="hljs-keyword">String</span> hashedRequestPayload = sha256Hex(payload);
<span class="hljs-keyword">String</span> canonicalRequest = httpRequestMethod + <span class="hljs-string">"\n"</span> + canonicalUri + <span class="hljs-string">"\n"</span> + canonicalQueryString + <span class="hljs-string">"\n"</span>
+ canonicalHeaders + <span class="hljs-string">"\n"</span> + signedHeaders + <span class="hljs-string">"\n"</span> + hashedRequestPayload;
System.out.<span class="hljs-built_in">println</span>(canonicalRequest);
<span class="hljs-comment">// ************* Step 2: Concatenate the string to sign *************</span>
<span class="hljs-keyword">String</span> credentialScope = date + <span class="hljs-string">"/"</span> + service + <span class="hljs-string">"/"</span> + <span class="hljs-string">"tc3_request"</span>;
<span class="hljs-keyword">String</span> hashedCanonicalRequest = sha256Hex(canonicalRequest);
<span class="hljs-keyword">String</span> stringToSign = algorithm + <span class="hljs-string">"\n"</span> + timestamp + <span class="hljs-string">"\n"</span> + credentialScope + <span class="hljs-string">"\n"</span> + hashedCanonicalRequest;
System.out.<span class="hljs-built_in">println</span>(stringToSign);
<span class="hljs-comment">// ************* Step 3: Calculate the signature *************</span>
<span class="hljs-built_in">byte</span>[] secretDate = hmac256((<span class="hljs-string">"TC3"</span> + SECRET_KEY).getBytes(UTF8), date);
<span class="hljs-built_in">byte</span>[] secretService = hmac256(secretDate, service);
<span class="hljs-built_in">byte</span>[] secretSigning = hmac256(secretService, <span class="hljs-string">"tc3_request"</span>);
<span class="hljs-keyword">String</span> signature = DatatypeConverter.printHexBinary(hmac256(secretSigning, stringToSign)).toLowerCase();
System.out.<span class="hljs-built_in">println</span>(signature);
<span class="hljs-comment">// ************* Step 4: Concatenate the Authorization *************</span>
<span class="hljs-keyword">String</span> authorization = algorithm + <span class="hljs-string">" "</span> + <span class="hljs-string">"Credential="</span> + SECRET_ID + <span class="hljs-string">"/"</span> + credentialScope + <span class="hljs-string">", "</span>
+ <span class="hljs-string">"SignedHeaders="</span> + signedHeaders + <span class="hljs-string">", "</span> + <span class="hljs-string">"Signature="</span> + signature;
System.out.<span class="hljs-built_in">println</span>(authorization);
TreeMap<<span class="hljs-keyword">String</span>, <span class="hljs-keyword">String</span>> headers = <span class="hljs-keyword">new</span> TreeMap<<span class="hljs-keyword">String</span>, <span class="hljs-keyword">String</span>>();
headers.put(<span class="hljs-string">"Authorization"</span>, authorization);
headers.put(<span class="hljs-string">"Content-Type"</span>, CT_JSON);
headers.put(<span class="hljs-string">"Host"</span>, host);
headers.put(<span class="hljs-string">"X-TC-Action"</span>, action);
headers.put(<span class="hljs-string">"X-TC-Timestamp"</span>, timestamp);
headers.put(<span class="hljs-string">"X-TC-Version"</span>, version);
headers.put(<span class="hljs-string">"X-TC-Region"</span>, region);
StringBuilder sb = <span class="hljs-keyword">new</span> StringBuilder();
sb.<span class="hljs-built_in">append</span>(<span class="hljs-string">"curl -X POST https://"</span>).<span class="hljs-built_in">append</span>(host)
.<span class="hljs-built_in">append</span>(<span class="hljs-string">" -H \"Authorization: "</span>).<span class="hljs-built_in">append</span>(authorization).<span class="hljs-built_in">append</span>(<span class="hljs-string">"\""</span>)
.<span class="hljs-built_in">append</span>(<span class="hljs-string">" -H \"Content-Type: application/json; charset=utf-8\""</span>)
.<span class="hljs-built_in">append</span>(<span class="hljs-string">" -H \"Host: "</span>).<span class="hljs-built_in">append</span>(host).<span class="hljs-built_in">append</span>(<span class="hljs-string">"\""</span>)
.<span class="hljs-built_in">append</span>(<span class="hljs-string">" -H \"X-TC-Action: "</span>).<span class="hljs-built_in">append</span>(action).<span class="hljs-built_in">append</span>(<span class="hljs-string">"\""</span>)
.<span class="hljs-built_in">append</span>(<span class="hljs-string">" -H \"X-TC-Timestamp: "</span>).<span class="hljs-built_in">append</span>(timestamp).<span class="hljs-built_in">append</span>(<span class="hljs-string">"\""</span>)
.<span class="hljs-built_in">append</span>(<span class="hljs-string">" -H \"X-TC-Version: "</span>).<span class="hljs-built_in">append</span>(version).<span class="hljs-built_in">append</span>(<span class="hljs-string">"\""</span>)
.<span class="hljs-built_in">append</span>(<span class="hljs-string">" -H \"X-TC-Region: "</span>).<span class="hljs-built_in">append</span>(region).<span class="hljs-built_in">append</span>(<span class="hljs-string">"\""</span>)
.<span class="hljs-built_in">append</span>(<span class="hljs-string">" -d '"</span>).<span class="hljs-built_in">append</span>(payload).<span class="hljs-built_in">append</span>(<span class="hljs-string">"'"</span>);
System.out.<span class="hljs-built_in">println</span>(sb.toString());
}
}
# -*- coding: utf-8 -*-
import hashlib, hmac, json, os, sys, time
from datetime import datetime
Key Parameters
secret_id = "AKID****"
secret_key = "****"
service = "cvm"
host = "cvm.tencentcloudapi.com"
endpoint = "https://" + host
region = "ap-guangzhou"
action = "DescribeInstances"
version = "2017-03-12"
algorithm = "TC3-HMAC-SHA256"
#timestamp = int(time.time())
timestamp = 1551113065
date = datetime.utcfromtimestamp(timestamp).strftime("%Y-%m-%d")
params = {"Limit": 1, "Filters": [{"Values": ["unnamed"], "Name": "instance-name"}]}
* Step 1: Concatenate the CanonicalRequest string *
http_request_method = "POST"
canonical_uri = "/"
canonical_querystring = ""
ct = "application/json; charset=utf-8"
payload = json.dumps(params)
canonical_headers = "content-type:%s\nhost:%s\n" % (ct, host)
signed_headers = "content-type;host"
hashed_request_payload = hashlib.sha256(payload.encode("utf-8")).hexdigest()
canonical_request = (http_request_method + "\n" +
canonical_uri + "\n" +
canonical_querystring + "\n" +
canonical_headers + "\n" +
signed_headers + "\n" +
hashed_request_payload)
print(canonical_request)
* Step 2: Concatenate the string to sign *
credential_scope = date + "/" + service + "/" + "tc3_request"
hashed_canonical_request = hashlib.sha256(canonical_request.encode("utf-8")).hexdigest()
string_to_sign = (algorithm + "\n" +
str(timestamp) + "\n" +
credential_scope + "\n" +
hashed_canonical_request)
print(string_to_sign)
* Step 3: Calculate the Signature *
Function for computing signature digest
def sign(key, msg):
return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()
secret_date = sign(("TC3" + secret_key).encode("utf-8"), date)
secret_service = sign(secret_date, service)
secret_signing = sign(secret_service, "tc3_request")
signature = hmac.new(secret_signing, string_to_sign.encode("utf-8"), hashlib.sha256).hexdigest()
print(signature)
* Step 4: Concatenate the Authorization *
authorization = (algorithm + " " +
"Credential=" + secret_id + "/" + credential_scope + ", " +
"SignedHeaders=" + signed_headers + ", " +
"Signature=" + signature)
print(authorization)
print('curl -X POST ' + endpoint
+ <span class="hljs-string">' -H "Authorization: '</span> + authorization <span class="hljs-comment">+</span> <span class="hljs-comment">'"'</span>
+ <span class="hljs-string">' -H "Content-Type: application/json; charset=utf-8"'</span>
+ <span class="hljs-string">' -H "Host: '</span> + host <span class="hljs-comment">+</span> <span class="hljs-comment">'"'</span>
+ <span class="hljs-string">' -H "X-TC-Action: '</span> + action <span class="hljs-comment">+</span> <span class="hljs-comment">'"'</span>
+ <span class="hljs-string">' -H "X-TC-Timestamp: '</span> + str(timestamp) <span class="hljs-comment">+</span> <span class="hljs-comment">'"'</span>
+ <span class="hljs-string">' -H "X-TC-Version: '</span> + version <span class="hljs-comment">+</span> <span class="hljs-comment">'"'</span>
+ <span class="hljs-string">' -H "X-TC-Region: '</span> + region <span class="hljs-comment">+</span> <span class="hljs-comment">'"'</span>
+ <span class="hljs-string">" -d '"</span> + payload <span class="hljs-comment">+</span> <span class="hljs-comment">"'"</span><span class="hljs-comment">)</span>
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"time"
)
func sha256hex(s string) string {
b := sha256.Sum256([]byte(s))
return hex.EncodeToString(b[:])
}
func hmacsha256(s, key string) string {
hashed := hmac.New(sha256.New, []byte(key))
hashed.Write([]byte(s))
return string(hashed.Sum(nil))
}
func main() {
secretId := "AKID****"
secretKey := "****"
host := "cvm.tencentcloudapi.com"
algorithm := "TC3-HMAC-SHA256"
service := "cvm"
version := "2017-03-12"
action := "DescribeInstances"
region := "ap-guangzhou"
//var timestamp int64 = time.Now().Unix()
var timestamp int64 = 1551113065
<span class="hljs-comment">// step 1: build canonical request string</span>
httpRequestMethod := <span class="hljs-string">"POST"</span>
canonicalURI := <span class="hljs-string">"/"</span>
canonicalQueryString := <span class="hljs-string">""</span>
canonicalHeaders := <span class="hljs-string">"content-type:application/json; charset=utf-8\n"</span> + <span class="hljs-string">"host:"</span> + host + <span class="hljs-string">"\n"</span>
signedHeaders := <span class="hljs-string">"content-type;host"</span>
payload := <span class="hljs-string">`{"Limit": 1, "Filters": [{"Values": ["unnamed"], "Name": "instance-name"}]}`</span>
hashedRequestPayload := sha256hex(payload)
canonicalRequest := fmt.Sprintf(<span class="hljs-string">"%s\n%s\n%s\n%s\n%s\n%s"</span>,
httpRequestMethod,
canonicalURI,
canonicalQueryString,
canonicalHeaders,
signedHeaders,
hashedRequestPayload)
fmt.Println(canonicalRequest)
<span class="hljs-comment">// step 2: build string to sign</span>
date := time.Unix(timestamp, <span class="hljs-number">0</span>).UTC().Format(<span class="hljs-string">"2006-01-02"</span>)
credentialScope := fmt.Sprintf(<span class="hljs-string">"%s/%s/tc3_request"</span>, date, service)
hashedCanonicalRequest := sha256hex(canonicalRequest)
string2sign := fmt.Sprintf(<span class="hljs-string">"%s\n%d\n%s\n%s"</span>,
algorithm,
timestamp,
credentialScope,
hashedCanonicalRequest)
fmt.Println(string2sign)
<span class="hljs-comment">// step 3: sign string</span>
secretDate := hmacsha256(date, <span class="hljs-string">"TC3"</span>+secretKey)
secretService := hmacsha256(service, secretDate)
secretSigning := hmacsha256(<span class="hljs-string">"tc3_request"</span>, secretService)
signature := hex.EncodeToString([]<span class="hljs-keyword">byte</span>(hmacsha256(string2sign, secretSigning)))
fmt.Println(signature)
<span class="hljs-comment">// step 4: build authorization</span>
authorization := fmt.Sprintf(<span class="hljs-string">"%s Credential=%s/%s, SignedHeaders=%s, Signature=%s"</span>,
algorithm,
secretId,
credentialScope,
signedHeaders,
signature)
fmt.Println(authorization)
curl := fmt.Sprintf(<span class="hljs-string">`curl -X POST https://%s\
-H "Authorization: %s"
-H "Content-Type: application/json; charset=utf-8"
-H "Host: %s" -H "X-TC-Action: %s"
-H "X-TC-Timestamp: %d"
-H "X-TC-Version: %s"
-H "X-TC-Region: %s"
-d '%s'`, host, authorization, host, action, timestamp, version, region, payload)
fmt.Println(curl)
}
<?php
$secretId = "AKID********************************";
$secretKey = "********************************";
$host = "cvm.tencentcloudapi.com";
$service = "cvm";
$version = "2017-03-12";
$action = "DescribeInstances";
$region = "ap-guangzhou";
// $timestamp = time();
$timestamp = 1551113065;
$algorithm = "TC3-HMAC-SHA256";
// step 1: build canonical request string
$httpRequestMethod = "POST";
$canonicalUri = "/";
$canonicalQueryString = "";
$canonicalHeaders = "content-type:application/json; charset=utf-8\n"."host:".$host."\n";
$signedHeaders = "content-type;host";
$payload = '{"Limit": 1, "Filters": [{"Values": ["unnamed"], "Name": "instance-name"}]}';
$hashedRequestPayload = hash("SHA256", $payload);
$canonicalRequest = $httpRequestMethod."\n"
.$canonicalUri."\n"
.$canonicalQueryString."\n"
.$canonicalHeaders."\n"
.$signedHeaders."\n"
.$hashedRequestPayload;
echo $canonicalRequest.PHP_EOL;
// step 2: build string to sign
$date = gmdate("Y-m-d", $timestamp);
$credentialScope = $date."/".$service."/tc3_request";
$hashedCanonicalRequest = hash("SHA256", $canonicalRequest);
$stringToSign = $algorithm."\n"
.$timestamp."\n"
.$credentialScope."\n"
.$hashedCanonicalRequest;
echo $stringToSign.PHP_EOL;
// step 3: sign string
$secretDate = hash_hmac("SHA256", $date, "TC3".$secretKey, true);
$secretService = hash_hmac("SHA256", $service, $secretDate, true);
$secretSigning = hash_hmac("SHA256", "tc3_request", $secretService, true);
$signature = hash_hmac("SHA256", $stringToSign, $secretSigning);
echo $signature.PHP_EOL;
// step 4: build authorization
$authorization = $algorithm
." Credential=".$secretId."/".$credentialScope
.", SignedHeaders=content-type;host, Signature=".$signature;
echo $authorization.PHP_EOL;
$curl = "curl -X POST https://".$host
.' -H "Authorization: '.$authorization.'"'
.' -H "Content-Type: application/json; charset=utf-8"'
.' -H "Host: '.$host.'"'
.' -H "X-TC-Action: '.$action.'"'
.' -H "X-TC-Timestamp: '.$timestamp.'"'
.' -H "X-TC-Version: '.$version.'"'
.' -H "X-TC-Region: '.$region.'"'
." -d '".$payload."'";
echo $curl.PHP_EOL;
# -*- coding: UTF-8 -*-
# require ruby>=2.3.0
require 'digest'
require 'json'
require 'time'
require 'openssl'
Key Parameters
secret_id = 'AKID****'
secret_key = '****'
service = 'cvm'
host = 'cvm.tencentcloudapi.com'
endpoint = 'https://' + host
region = 'ap-guangzhou'
action = 'DescribeInstances'
version = '2017-03-12'
algorithm = 'TC3-HMAC-SHA256'
timestamp = Time.now.to_i
timestamp = 1551113065
date = Time.at(timestamp).utc.strftime('%Y-%m-%d')
* Step 1: Concatenate the CanonicalRequest string *
http_request_method = 'POST'
canonical_uri = '/'
canonical_querystring = ''
canonical_headers = "content-type:application/json; charset=utf-8\nhost:#{host}\n"
signed_headers = 'content-type;host'
params = { 'Limit' => 1, 'Filters' => [{ 'Name' => 'instance-name', 'Values' => ['unnamed'] }] }
payload = JSON.generate(params, { 'ascii_only' => true, 'space' => ' ' })
json will generate in random order, to get specified result in example, we hard-code it here.
payload = '{"Limit": 1, "Filters": [{"Values": ["unnamed"], "Name": "instance-name"}]}'
hashed_request_payload = Digest::SHA256.hexdigest(payload)
canonical_request = [
http_request_method,
canonical_uri,
canonical_querystring,
canonical_headers,
signed_headers,
hashed_request_payload,
].join("\n")
puts canonical_request
* Step 2: Concatenate the string to sign *
credential_scope = date + '/' + service + '/' + 'tc3_request'
hashed_request_payload = Digest::SHA256.hexdigest(canonical_request)
string_to_sign = [
algorithm,
timestamp.to_s,
credential_scope,
hashed_request_payload,
].join("\n")
puts string_to_sign
* Step 3: Calculate the Signature *
digest = OpenSSL::Digest.new('sha256')
secret_date = OpenSSL::HMAC.digest(digest, 'TC3' + secret_key, date)
secret_service = OpenSSL::HMAC.digest(digest, secret_date, service)
secret_signing = OpenSSL::HMAC.digest(digest, secret_service, 'tc3_request')
signature = OpenSSL::HMAC.hexdigest(digest, secret_signing, string_to_sign)
puts signature
* Step 4: Concatenate the Authorization *
authorization = "#{algorithm} Credential=#{secret_id}/#{credential_scope}, SignedHeaders=#{signed_headers}, Signature=#{signature}"
puts authorization
puts 'curl -X POST ' + endpoint
+ <span class="hljs-string">' -H "Authorization: '</span> + authorization <span class="hljs-comment">+</span> <span class="hljs-comment">'"'</span> <span class="hljs-comment">\</span>
+ <span class="hljs-string">' -H "Content-Type: application/json; charset=utf-8"'</span> \
+ <span class="hljs-string">' -H "Host: '</span> + host <span class="hljs-comment">+</span> <span class="hljs-comment">'"'</span> <span class="hljs-comment">\</span>
+ <span class="hljs-string">' -H "X-TC-Action: '</span> + action <span class="hljs-comment">+</span> <span class="hljs-comment">'"'</span> <span class="hljs-comment">\</span>
+ <span class="hljs-string">' -H "X-TC-Timestamp: '</span> + timestamp.to_s <span class="hljs-comment">+</span> <span class="hljs-comment">'"'</span> <span class="hljs-comment">\</span>
+ <span class="hljs-string">' -H "X-TC-Version: '</span> + version <span class="hljs-comment">+</span> <span class="hljs-comment">'"'</span> <span class="hljs-comment">\</span>
+ <span class="hljs-string">' -H "X-TC-Region: '</span> + region <span class="hljs-comment">+</span> <span class="hljs-comment">'"'</span> <span class="hljs-comment">\</span>
+ <span class="hljs-string">" -d '"</span> + payload <span class="hljs-comment">+</span> <span class="hljs-comment">"'"</span>
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
public class Application
{
public static string SHA256Hex(string s)
{
using (SHA256 algo = SHA256.Create())
{
byte[] hashbytes = algo.ComputeHash(Encoding.UTF8.GetBytes(s));
StringBuilder builder = new StringBuilder();
for (int i = 0; i < hashbytes.Length; ++i)
{
builder.Append(hashbytes[i].ToString("x2"));
}
return builder.ToString();
}
}
public static byte[] HmacSHA256(byte[] key, byte[] msg)
{
using (HMACSHA256 mac = new HMACSHA256(key))
{
return mac.ComputeHash(msg);
}
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Dictionary<String, String> <span class="hljs-title">BuildHeaders</span>(<span class="hljs-params"><span class="hljs-built_in">string</span> secretid,
<span class="hljs-built_in">string</span> secretkey, <span class="hljs-built_in">string</span> service, <span class="hljs-built_in">string</span> endpoint, <span class="hljs-built_in">string</span> region,
<span class="hljs-built_in">string</span> action, <span class="hljs-built_in">string</span> version, DateTime date, <span class="hljs-built_in">string</span> requestPayload</span>)</span>
{
<span class="hljs-built_in">string</span> datestr = date.ToString(<span class="hljs-string">"yyyy-MM-dd"</span>);
DateTime startTime = <span class="hljs-keyword">new</span> DateTime(<span class="hljs-number">1970</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, DateTimeKind.Utc);
<span class="hljs-built_in">long</span> requestTimestamp = (<span class="hljs-built_in">long</span>)Math.Round((date - startTime).TotalMilliseconds, MidpointRounding.AwayFromZero) / <span class="hljs-number">1000</span>;
<span class="hljs-comment">// ************* Step 1: Concatenate the CanonicalRequest string *************</span>
<span class="hljs-built_in">string</span> algorithm = <span class="hljs-string">"TC3-HMAC-SHA256"</span>;
<span class="hljs-built_in">string</span> httpRequestMethod = <span class="hljs-string">"POST"</span>;
<span class="hljs-built_in">string</span> canonicalUri = <span class="hljs-string">"/"</span>;
<span class="hljs-built_in">string</span> canonicalQueryString = <span class="hljs-string">""</span>;
<span class="hljs-built_in">string</span> contentType = <span class="hljs-string">"application/json"</span>;
<span class="hljs-built_in">string</span> canonicalHeaders = <span class="hljs-string">"content-type:"</span> + contentType + <span class="hljs-string">"; charset=utf-8\n"</span> + <span class="hljs-string">"host:"</span> + endpoint + <span class="hljs-string">"\n"</span>;
<span class="hljs-built_in">string</span> signedHeaders = <span class="hljs-string">"content-type;host"</span>;
<span class="hljs-built_in">string</span> hashedRequestPayload = SHA256Hex(requestPayload);
<span class="hljs-built_in">string</span> canonicalRequest = httpRequestMethod + <span class="hljs-string">"\n"</span>
+ canonicalUri + <span class="hljs-string">"\n"</span>
+ canonicalQueryString + <span class="hljs-string">"\n"</span>
+ canonicalHeaders + <span class="hljs-string">"\n"</span>
+ signedHeaders + <span class="hljs-string">"\n"</span>
+ hashedRequestPayload;
Console.WriteLine(canonicalRequest);
Console.WriteLine(<span class="hljs-string">"----------------------------------"</span>);
<span class="hljs-comment">// ************ Step 2: Concatenate the string to sign *************</span>
<span class="hljs-built_in">string</span> credentialScope = datestr + <span class="hljs-string">"/"</span> + service + <span class="hljs-string">"/"</span> + <span class="hljs-string">"tc3_request"</span>;
<span class="hljs-built_in">string</span> hashedCanonicalRequest = SHA256Hex(canonicalRequest);
<span class="hljs-built_in">string</span> stringToSign = algorithm + <span class="hljs-string">"\n"</span> + requestTimestamp.ToString() + <span class="hljs-string">"\n"</span> + credentialScope + <span class="hljs-string">"\n"</span> + hashedCanonicalRequest;
Console.WriteLine(stringToSign);
Console.WriteLine(<span class="hljs-string">"----------------------------------"</span>);
<span class="hljs-comment">// ************* Step 3: Calculate the signature *************</span>
<span class="hljs-built_in">byte</span>[] tc3SecretKey = Encoding.UTF8.GetBytes(<span class="hljs-string">"TC3"</span> + secretkey);
<span class="hljs-built_in">byte</span>[] secretDate = HmacSHA256(tc3SecretKey, Encoding.UTF8.GetBytes(datestr));
<span class="hljs-built_in">byte</span>[] secretService = HmacSHA256(secretDate, Encoding.UTF8.GetBytes(service));
<span class="hljs-built_in">byte</span>[] secretSigning = HmacSHA256(secretService, Encoding.UTF8.GetBytes(<span class="hljs-string">"tc3_request"</span>));
<span class="hljs-built_in">byte</span>[] signatureBytes = HmacSHA256(secretSigning, Encoding.UTF8.GetBytes(stringToSign));
<span class="hljs-built_in">string</span> signature = BitConverter.ToString(signatureBytes).Replace(<span class="hljs-string">"-"</span>, <span class="hljs-string">""</span>).ToLower();
Console.WriteLine(signature);
Console.WriteLine(<span class="hljs-string">"----------------------------------"</span>);
<span class="hljs-comment">// ************* Step 4: Concatenate the Authorization *************</span>
<span class="hljs-built_in">string</span> authorization = algorithm + <span class="hljs-string">" "</span>
+ <span class="hljs-string">"Credential="</span> + secretid + <span class="hljs-string">"/"</span> + credentialScope + <span class="hljs-string">", "</span>
+ <span class="hljs-string">"SignedHeaders="</span> + signedHeaders + <span class="hljs-string">", "</span>
+ <span class="hljs-string">"Signature="</span> + signature;
Console.WriteLine(authorization);
Console.WriteLine(<span class="hljs-string">"----------------------------------"</span>);
Dictionary<<span class="hljs-built_in">string</span>, <span class="hljs-built_in">string</span>> headers = <span class="hljs-keyword">new</span> Dictionary<<span class="hljs-built_in">string</span>, <span class="hljs-built_in">string</span>>();
headers.Add(<span class="hljs-string">"Authorization"</span>, authorization);
headers.Add(<span class="hljs-string">"Host"</span>, endpoint);
headers.Add(<span class="hljs-string">"Content-Type"</span>, contentType + <span class="hljs-string">"; charset=utf-8"</span>);
headers.Add(<span class="hljs-string">"X-TC-Timestamp"</span>, requestTimestamp.ToString());
headers.Add(<span class="hljs-string">"X-TC-Version"</span>, version);
headers.Add(<span class="hljs-string">"X-TC-Action"</span>, action);
headers.Add(<span class="hljs-string">"X-TC-Region"</span>, region);
<span class="hljs-keyword">return</span> headers;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-built_in">string</span>[] args</span>)</span>
{
<span class="hljs-comment">// SecretID and SecretKey</span>
<span class="hljs-built_in">string</span> SECRET_ID = <span class="hljs-string">"AKID********************************"</span>;
<span class="hljs-built_in">string</span> SECRET_KEY = <span class="hljs-string">"********************************"</span>;
<span class="hljs-built_in">string</span> service = <span class="hljs-string">"cvm"</span>;
<span class="hljs-built_in">string</span> endpoint = <span class="hljs-string">"cvm.tencentcloudapi.com"</span>;
<span class="hljs-built_in">string</span> region = <span class="hljs-string">"ap-guangzhou"</span>;
<span class="hljs-built_in">string</span> action = <span class="hljs-string">"DescribeInstances"</span>;
<span class="hljs-built_in">string</span> version = <span class="hljs-string">"2017-03-12"</span>;
<span class="hljs-comment">// The timestamp `2019-02-26 00:44:25` used here is only for reference. In a project, use the following parameter:</span>
<span class="hljs-comment">// DateTime date = DateTime.UtcNow;</span>
<span class="hljs-comment">// Enter the correct time zone. We recommend using UTC timestamp to avoid errors.</span>
DateTime date = <span class="hljs-keyword">new</span> DateTime(<span class="hljs-number">1970</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, DateTimeKind.Utc).AddSeconds(<span class="hljs-number">1551113065</span>);
<span class="hljs-built_in">string</span> requestPayload = <span class="hljs-string">"{\"Limit\": 1, \"Filters\": [{\"Values\": [\"unnamed\"], \"Name\": \"instance-name\"}]}"</span>;
Dictionary<<span class="hljs-built_in">string</span>, <span class="hljs-built_in">string</span>> headers = BuildHeaders(SECRET_ID, SECRET_KEY, service
, endpoint, region, action, version, date, requestPayload);
Console.WriteLine(<span class="hljs-string">"POST https://cvm.tencentcloudapi.com"</span>);
<span class="hljs-keyword">foreach</span> (KeyValuePair<<span class="hljs-built_in">string</span>, <span class="hljs-built_in">string</span>> kv <span class="hljs-keyword">in</span> headers)
{
Console.WriteLine(kv.Key + <span class="hljs-string">": "</span> + kv.Value);
}
Console.WriteLine();
Console.WriteLine(requestPayload);
}
}
const crypto = require('crypto');
function sha256(message, secret = '', encoding) {
const hmac = crypto.createHmac('sha256', secret)
return hmac.update(message).digest(encoding)
}
function getHash(message, encoding = 'hex') {
const hash = crypto.createHash('sha256')
return hash.update(message).digest(encoding)
}
function getDate(timestamp) {
const date = new Date(timestamp * 1000)
const year = date.getUTCFullYear()
const month = ('0' + (date.getUTCMonth() + 1)).slice(-2)
const day = ('0' + date.getUTCDate()).slice(-2)
return <span class="hljs-subst">${year}</span>-<span class="hljs-subst">${month}</span>-<span class="hljs-subst">${day}</span>
}
function main(){
<span class="hljs-keyword">const</span> SECRET_ID = <span class="hljs-string">"AKID********************************"</span>
<span class="hljs-keyword">const</span> SECRET_KEY = <span class="hljs-string">"********************************"</span>
<span class="hljs-keyword">const</span> endpoint = <span class="hljs-string">"cvm.tencentcloudapi.com"</span>
<span class="hljs-keyword">const</span> service = <span class="hljs-string">"cvm"</span>
<span class="hljs-keyword">const</span> region = <span class="hljs-string">"ap-guangzhou"</span>
<span class="hljs-keyword">const</span> action = <span class="hljs-string">"DescribeInstances"</span>
<span class="hljs-keyword">const</span> version = <span class="hljs-string">"2017-03-12"</span>
<span class="hljs-comment">//const timestamp = getTime()</span>
<span class="hljs-keyword">const</span> timestamp = <span class="hljs-number">1551113065</span>
<span class="hljs-keyword">const</span> <span class="hljs-built_in">date</span> = getDate(timestamp)
<span class="hljs-comment">// ************* Step 1: Concatenate the CanonicalRequest string *************</span>
<span class="hljs-keyword">const</span> signedHeaders = <span class="hljs-string">"content-type;host"</span>
<span class="hljs-keyword">const</span> payload = <span class="hljs-string">"{\"Limit\": 1, \"Filters\": [{\"Values\": [\"unnamed\"], \"Name\": \"instance-name\"}]}"</span>
<span class="hljs-keyword">const</span> hashedRequestPayload = getHash(payload);
<span class="hljs-keyword">const</span> httpRequestMethod = <span class="hljs-string">"POST"</span>
<span class="hljs-keyword">const</span> canonicalUri = <span class="hljs-string">"/"</span>
<span class="hljs-keyword">const</span> canonicalQueryString = <span class="hljs-string">""</span>
<span class="hljs-keyword">const</span> canonicalHeaders = <span class="hljs-string">"content-type:application/json; charset=utf-8\n"</span> + <span class="hljs-string">"host:"</span> + endpoint + <span class="hljs-string">"\n"</span>
<span class="hljs-keyword">const</span> canonicalRequest = httpRequestMethod + <span class="hljs-string">"\n"</span>
+ canonicalUri + <span class="hljs-string">"\n"</span>
+ canonicalQueryString + <span class="hljs-string">"\n"</span>
+ canonicalHeaders + <span class="hljs-string">"\n"</span>
+ signedHeaders + <span class="hljs-string">"\n"</span>
+ hashedRequestPayload
<span class="hljs-built_in">console</span>.log(canonicalRequest)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"----------------------------"</span>)
<span class="hljs-comment">// ************* Step 2: Concatenate the string to sign *************</span>
<span class="hljs-keyword">const</span> algorithm = <span class="hljs-string">"TC3-HMAC-SHA256"</span>
<span class="hljs-keyword">const</span> hashedCanonicalRequest = getHash(canonicalRequest);
<span class="hljs-keyword">const</span> credentialScope = <span class="hljs-built_in">date</span> + <span class="hljs-string">"/"</span> + service + <span class="hljs-string">"/"</span> + <span class="hljs-string">"tc3_request"</span>
<span class="hljs-keyword">const</span> stringToSign = algorithm + <span class="hljs-string">"\n"</span> +
timestamp + <span class="hljs-string">"\n"</span> +
credentialScope + <span class="hljs-string">"\n"</span> +
hashedCanonicalRequest
<span class="hljs-built_in">console</span>.log(stringToSign)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"----------------------------"</span>)
<span class="hljs-comment">// ************* Step 3: Calculate the signature *************</span>
<span class="hljs-keyword">const</span> kDate = sha256(<span class="hljs-built_in">date</span>, <span class="hljs-string">'TC3'</span> + SECRET_KEY)
<span class="hljs-keyword">const</span> kService = sha256(service, kDate)
<span class="hljs-keyword">const</span> kSigning = sha256(<span class="hljs-string">'tc3_request'</span>, kService)
<span class="hljs-keyword">const</span> signature = sha256(stringToSign, kSigning, <span class="hljs-string">'hex'</span>)
<span class="hljs-built_in">console</span>.log(signature)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"----------------------------"</span>)
<span class="hljs-comment">// ************* Step 4: Concatenate the Authorization *************</span>
<span class="hljs-keyword">const</span> authorization = algorithm + <span class="hljs-string">" "</span> +
<span class="hljs-string">"Credential="</span> + SECRET_ID + <span class="hljs-string">"/"</span> + credentialScope + <span class="hljs-string">", "</span> +
<span class="hljs-string">"SignedHeaders="</span> + signedHeaders + <span class="hljs-string">", "</span> +
<span class="hljs-string">"Signature="</span> + signature
<span class="hljs-built_in">console</span>.log(authorization)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"----------------------------"</span>)
<span class="hljs-keyword">const</span> Call_Information = <span class="hljs-string">'curl -X POST '</span> + <span class="hljs-string">"https://"</span> + endpoint
+ <span class="hljs-string">' -H "Authorization: '</span> + authorization + <span class="hljs-string">'"'</span>
+ <span class="hljs-string">' -H "Content-Type: application/json; charset=utf-8"'</span>
+ <span class="hljs-string">' -H "Host: '</span> + endpoint + <span class="hljs-string">'"'</span>
+ <span class="hljs-string">' -H "X-TC-Action: '</span> + action + <span class="hljs-string">'"'</span>
+ <span class="hljs-string">' -H "X-TC-Timestamp: '</span> + timestamp.toString() + <span class="hljs-string">'"'</span>
+ <span class="hljs-string">' -H "X-TC-Version: '</span> + version + <span class="hljs-string">'"'</span>
+ <span class="hljs-string">' -H "X-TC-Region: '</span> + region + <span class="hljs-string">'"'</span>
+ <span class="hljs-string">" -d '"</span> + payload + <span class="hljs-string">"'"</span>
<span class="hljs-built_in">console</span>.log(Call_Information)
}
main()
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <stdio.h>
#include <time.h>
#include <openssl/sha.h>
#include <openssl/hmac.h>
using namespace std;
string get_data(int64_t ×tamp)
{
string utcDate;
char buff[20] = {0};
// time_t timenow;
struct tm sttime;
sttime = *gmtime(×tamp);
strftime(buff, sizeof(buff), "%Y-%m-%d", &sttime);
utcDate = string(buff);
return utcDate;
}
string int2str(int64_t n)
{
std::stringstream ss;
ss << n;
return ss.str();
}
string sha256Hex(const string &str)
{
char buf[3];
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, str.c_str(), str.size());
SHA256_Final(hash, &sha256);
std::string NewString = "";
for(int i = 0; i < SHA256_DIGEST_LENGTH; i++)
{
snprintf(buf, sizeof(buf), "%02x", hash[i]);
NewString = NewString + buf;
}
return NewString;
}
string HmacSha256(const string &key, const string &input)
{
unsigned char hash[32];
HMAC_CTX *h;
#if OPENSSL_VERSION_NUMBER < 0x10100000L
HMAC_CTX hmac;
HMAC_CTX_init(&hmac);
h = &hmac;
#else
h = HMAC_CTX_new();
#endif
<span class="hljs-built_in">HMAC_Init_ex</span>(h, &key[<span class="hljs-number">0</span>], key.<span class="hljs-built_in">length</span>(), <span class="hljs-built_in">EVP_sha256</span>(), <span class="hljs-literal">NULL</span>);
<span class="hljs-built_in">HMAC_Update</span>(h, ( <span class="hljs-keyword">unsigned</span> <span class="hljs-keyword">char</span>* )&input[<span class="hljs-number">0</span>], input.<span class="hljs-built_in">length</span>());
<span class="hljs-keyword">unsigned</span> <span class="hljs-keyword">int</span> len = <span class="hljs-number">32</span>;
<span class="hljs-built_in">HMAC_Final</span>(h, hash, &len);
#if OPENSSL_VERSION_NUMBER < 0x10100000L
HMAC_CTX_cleanup(h);
#else
HMAC_CTX_free(h);
#endif
std::stringstream ss;
ss << std::<span class="hljs-built_in">setfill</span>(<span class="hljs-string">'0'</span>);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i < len; i++)
{
ss << hash[i];
}
<span class="hljs-keyword">return</span> (ss.<span class="hljs-built_in">str</span>());
}
string HexEncode(const string &input)
{
static const char* const lut = "0123456789abcdef";
size_t len = input.length();
string output;
output.<span class="hljs-built_in">reserve</span>(<span class="hljs-number">2</span> * len);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">size_t</span> i = <span class="hljs-number">0</span>; i < len; ++i)
{
<span class="hljs-keyword">const</span> <span class="hljs-keyword">unsigned</span> <span class="hljs-keyword">char</span> c = input[i];
output.<span class="hljs-built_in">push_back</span>(lut[c >> <span class="hljs-number">4</span>]);
output.<span class="hljs-built_in">push_back</span>(lut[c & <span class="hljs-number">15</span>]);
}
<span class="hljs-keyword">return</span> output;
}
int main()
{
string SECRET_ID = "AKID****";
string SECRET_KEY = "****";
string service = <span class="hljs-string">"cvm"</span>;
string host = <span class="hljs-string">"cvm.tencentcloudapi.com"</span>;
string region = <span class="hljs-string">"ap-guangzhou"</span>;
string action = <span class="hljs-string">"DescribeInstances"</span>;
string version = <span class="hljs-string">"2017-03-12"</span>;
<span class="hljs-keyword">int64_t</span> timestamp = <span class="hljs-number">1551113065</span>;
string date = <span class="hljs-built_in">get_data</span>(timestamp);
<span class="hljs-comment">// ************* Step 1: Concatenate the CanonicalRequest string *************</span>
string httpRequestMethod = <span class="hljs-string">"POST"</span>;
string canonicalUri = <span class="hljs-string">"/"</span>;
string canonicalQueryString = <span class="hljs-string">""</span>;
string canonicalHeaders = <span class="hljs-string">"content-type:application/json; charset=utf-8\nhost:"</span> + host + <span class="hljs-string">"\n"</span>;
string signedHeaders = <span class="hljs-string">"content-type;host"</span>;
string payload = <span class="hljs-string">"{\"Limit\": 1, \"Filters\": [{\"Values\": [\"unnamed\"], \"Name\": \"instance-name\"}]}"</span>;
string hashedRequestPayload = <span class="hljs-built_in">sha256Hex</span>(payload);
string canonicalRequest = httpRequestMethod + <span class="hljs-string">"\n"</span> + canonicalUri + <span class="hljs-string">"\n"</span> + canonicalQueryString + <span class="hljs-string">"\n"</span>
+ canonicalHeaders + <span class="hljs-string">"\n"</span> + signedHeaders + <span class="hljs-string">"\n"</span> + hashedRequestPayload;
cout << canonicalRequest << endl;
cout << <span class="hljs-string">"-----------------------"</span> << endl;
<span class="hljs-comment">// ************* Step 2: Concatenate the string to sign *************</span>
string algorithm = <span class="hljs-string">"TC3-HMAC-SHA256"</span>;
string RequestTimestamp = <span class="hljs-built_in">int2str</span>(timestamp);
string credentialScope = date + <span class="hljs-string">"/"</span> + service + <span class="hljs-string">"/"</span> + <span class="hljs-string">"tc3_request"</span>;
string hashedCanonicalRequest = <span class="hljs-built_in">sha256Hex</span>(canonicalRequest);
string stringToSign = algorithm + <span class="hljs-string">"\n"</span> + RequestTimestamp + <span class="hljs-string">"\n"</span> + credentialScope + <span class="hljs-string">"\n"</span> + hashedCanonicalRequest;
cout << stringToSign << endl;
cout << <span class="hljs-string">"-----------------------"</span> << endl;
<span class="hljs-comment">// ************* Step 3: Calculate the signature ***************</span>
string kKey = <span class="hljs-string">"TC3"</span> + SECRET_KEY;
string kDate = <span class="hljs-built_in">HmacSha256</span>(kKey, date);
string kService = <span class="hljs-built_in">HmacSha256</span>(kDate, service);
string kSigning = <span class="hljs-built_in">HmacSha256</span>(kService, <span class="hljs-string">"tc3_request"</span>);
string signature = <span class="hljs-built_in">HexEncode</span>(<span class="hljs-built_in">HmacSha256</span>(kSigning, stringToSign));
cout << signature << endl;
cout << <span class="hljs-string">"-----------------------"</span> << endl;
<span class="hljs-comment">// ************* Step 4: Concatenate the Authorization *************</span>
string authorization = algorithm + <span class="hljs-string">" "</span> + <span class="hljs-string">"Credential="</span> + SECRET_ID + <span class="hljs-string">"/"</span> + credentialScope + <span class="hljs-string">", "</span>
+ <span class="hljs-string">"SignedHeaders="</span> + signedHeaders + <span class="hljs-string">", "</span> + <span class="hljs-string">"Signature="</span> + signature;
cout << authorization << endl;
cout << <span class="hljs-string">"------------------------"</span> << endl;
string headers = <span class="hljs-string">"curl -X POST https://"</span> + host + <span class="hljs-string">"\n"</span>
+ <span class="hljs-string">" -H \"Authorization: "</span> + authorization + <span class="hljs-string">"\n"</span>
+ <span class="hljs-string">" -H \"Content-Type: application/json; charset=utf-8\""</span> + <span class="hljs-string">"\n"</span>
+ <span class="hljs-string">" -H \"Host: "</span> + host + <span class="hljs-string">"\n"</span>
+ <span class="hljs-string">" -H \"X-TC-Action: "</span> + action + <span class="hljs-string">"\n"</span>
+ <span class="hljs-string">" -H \"X-TC-Timestamp: "</span> + RequestTimestamp + <span class="hljs-string">"\n"</span>
+ <span class="hljs-string">" -H \"X-TC-Version: "</span> + version + <span class="hljs-string">"\n"</span>
+ <span class="hljs-string">" -H \"X-TC-Region: "</span> + region + <span class="hljs-string">"\n"</span>
+ <span class="hljs-string">" -d '"</span> + payload;
cout << headers << endl;
<span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
};
The following situational error codes for signature failure may occur. Please resolve the errors accordingly.
| Error Code | Description |
|---|---|
| AuthFailure.SignatureExpire | Signature expired. Timestamp and server time cannot differ by more than five minutes. |
| AuthFailure.SecretIdNotFound | The key does not exist. Please go to the console to check whether it is disabled or you copied fewer or more characters. |
| AuthFailure.SignatureFailure | Signature error. It is possible that the signature was calculated incorrectly, the signature does not match the content actually sent, or the SecretKey is incorrect. |
| AuthFailure.TokenFailure | Temporary certificate token error. |
| AuthFailure.InvalidSecretId | Invalid key (not a TencentCloud API key type). |
피드백