• 腾讯云v3签名的使用


    本文的目标是:用“签名方法 v3”调用“录音文件识别请求”接口

    v3文档中提供了各大编程语言的演示代码,选择合适自己的。

    其它接口的文档写得挺好懂的,示例代码复制过来就能用,

    就这个v3的文档,我感觉写不太明白,首次接触真的很懵逼!

    现在自己调用成功了特此来记录下。

    一、修改公共参数:

    v3中有这么几个参数:

    对应以下画圈圈的做修改:

    所以得到修改后的代码:

    string service = "asr";
    string endpoint = "asr.tencentcloudapi.com";
    string region = "";
    string action = "CreateRecTask";
    string version = "2019-06-14";

    二、修改提交参数

    v3中有这么一个变量(就是你要提交的参数的json格式):

    string requestPayload = "{"Limit": 1, "Filters": [{"Values": ["\u672a\u547d\u540d"], "Name": "instance-name"}]}";

    修改为目标接口的参数(按需提供、去掉公共参数):

    StringBuilder parameter = new StringBuilder();
    parameter.Append("{");
    parameter.Append(""EngineModelType":"16k_zh",");
    parameter.Append(""ChannelNum":1,");
    parameter.Append(""SourceType":1,");
    parameter.Append(""Data":"base64",");
    parameter.Append(""ResTextFormat":1,");
    parameter.Append(""FilterPunc":2");
    parameter.Append("}");
    string requestPayload = parameter.ToString();

    三、发送请求

    到这一步就OK了:

    var headers = Application.BuildHeaders(SECRET_ID, SECRET_KEY, service
        , endpoint, region, action, version, DateTime.UtcNow, requestPayload);
    
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create($"https://{endpoint}");
    request.Method = "post";
    
    foreach (KeyValuePair<string, string> kv in headers)
    {
        request.Headers.Add(kv.Key, kv.Value);
    }
    
    byte[] byteData = Encoding.UTF8.GetBytes(requestPayload);
    request.ContentLength = byteData.Length;
    
    using (Stream postStream = request.GetRequestStream())
    {
        postStream.Write(byteData, 0, byteData.Length);
    }
    
    WebResponse response = request.GetResponse();
    StreamReader reader = new StreamReader(response.GetResponseStream());
    string result = reader.ReadToEnd();
    
    response.Close();
    reader.Dispose();

    最后贴出完整代码:

      1 using System;
      2 using System.Collections.Generic;
      3 using System.IO;
      4 using System.Net;
      5 using System.Security.Cryptography;
      6 using System.Text;
      7 
      8 namespace ConsoleDemo
      9 {
     10     class Program
     11     {
     12         static void Main(string[] args)
     13         {
     14             // 填入你自己的密钥参数
     15             string SECRET_ID = "";
     16             string SECRET_KEY = "";
     17 
     18             string service = "asr";
     19             string endpoint = "asr.tencentcloudapi.com";
     20             string region = "";
     21             string action = "CreateRecTask";
     22             string version = "2019-06-14";
     23 
     24             StringBuilder parameter = new StringBuilder();
     25             parameter.Append("{");
     26             parameter.Append(""EngineModelType":"16k_zh",");
     27             parameter.Append(""ChannelNum":1,");
     28             parameter.Append(""SourceType":1,");
     29             parameter.Append(""Data":"base64",");
     30             parameter.Append(""ResTextFormat":1,");
     31             parameter.Append(""FilterPunc":2");
     32             parameter.Append("}");
     33             string requestPayload = parameter.ToString();
     34 
     35             var headers = Application.BuildHeaders(SECRET_ID, SECRET_KEY, service
     36                 , endpoint, region, action, version, DateTime.UtcNow, requestPayload);
     37 
     38             HttpWebRequest request = (HttpWebRequest)WebRequest.Create($"https://{endpoint}");
     39             request.Method = "post";
     40 
     41             foreach (KeyValuePair<string, string> kv in headers)
     42             {
     43                 request.Headers.Add(kv.Key, kv.Value);
     44             }
     45 
     46             byte[] byteData = Encoding.UTF8.GetBytes(requestPayload);
     47             request.ContentLength = byteData.Length;
     48 
     49             using (Stream postStream = request.GetRequestStream())
     50             {
     51                 postStream.Write(byteData, 0, byteData.Length);
     52             }
     53 
     54             WebResponse response = request.GetResponse();
     55             StreamReader reader = new StreamReader(response.GetResponseStream());
     56             string result = reader.ReadToEnd();
     57 
     58             response.Close();
     59             reader.Dispose();
     60         }
     61     }
     62 
     63     public class Application
     64     {
     65         public static string SHA256Hex(string s)
     66         {
     67             using (SHA256 algo = SHA256.Create())
     68             {
     69                 byte[] hashbytes = algo.ComputeHash(Encoding.UTF8.GetBytes(s));
     70                 StringBuilder builder = new StringBuilder();
     71                 for (int i = 0; i < hashbytes.Length; ++i)
     72                 {
     73                     builder.Append(hashbytes[i].ToString("x2"));
     74                 }
     75                 return builder.ToString();
     76             }
     77         }
     78 
     79         public static byte[] HmacSHA256(byte[] key, byte[] msg)
     80         {
     81             using (HMACSHA256 mac = new HMACSHA256(key))
     82             {
     83                 return mac.ComputeHash(msg);
     84             }
     85         }
     86 
     87         public static Dictionary<String, String> BuildHeaders(string secretid,
     88             string secretkey, string service, string endpoint, string region,
     89             string action, string version, DateTime date, string requestPayload)
     90         {
     91             string algorithm = "TC3-HMAC-SHA256";
     92             string datestr = date.ToString("yyyy-MM-dd");
     93             DateTime startTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
     94             long requestTimestamp = (long)Math.Round((date - startTime).TotalMilliseconds, MidpointRounding.AwayFromZero) / 1000;
     95 
     96             // ************* 步骤 1:拼接规范请求串 *************
     97             string httpRequestMethod = "POST";
     98             string canonicalUri = "/";
     99             string canonicalQueryString = "";
    100             string contentType = "application/json";
    101             string canonicalHeaders = "content-type:" + contentType + "; charset=utf-8
    " + "host:" + endpoint + "
    ";
    102             string signedHeaders = "content-type;host";
    103             string hashedRequestPayload = SHA256Hex(requestPayload);
    104             string canonicalRequest = httpRequestMethod + "
    "
    105                 + canonicalUri + "
    "
    106                 + canonicalQueryString + "
    "
    107                 + canonicalHeaders + "
    "
    108                 + signedHeaders + "
    "
    109                 + hashedRequestPayload;
    110             Console.WriteLine(canonicalRequest);
    111             Console.WriteLine("----------------------------------");
    112 
    113             // ************* 步骤 2:拼接待签名字符串 *************
    114             string credentialScope = datestr + "/" + service + "/" + "tc3_request";
    115             string hashedCanonicalRequest = SHA256Hex(canonicalRequest);
    116             string stringToSign = algorithm + "
    " + requestTimestamp.ToString() + "
    " + credentialScope + "
    " + hashedCanonicalRequest;
    117             Console.WriteLine(stringToSign);
    118             Console.WriteLine("----------------------------------");
    119 
    120             // ************* 步骤 3:计算签名 *************
    121             byte[] tc3SecretKey = Encoding.UTF8.GetBytes("TC3" + secretkey);
    122             byte[] secretDate = HmacSHA256(tc3SecretKey, Encoding.UTF8.GetBytes(datestr));
    123             byte[] secretService = HmacSHA256(secretDate, Encoding.UTF8.GetBytes(service));
    124             byte[] secretSigning = HmacSHA256(secretService, Encoding.UTF8.GetBytes("tc3_request"));
    125             byte[] signatureBytes = HmacSHA256(secretSigning, Encoding.UTF8.GetBytes(stringToSign));
    126             string signature = BitConverter.ToString(signatureBytes).Replace("-", "").ToLower();
    127             Console.WriteLine(signature);
    128             Console.WriteLine("----------------------------------");
    129 
    130             // ************* 步骤 4:拼接 Authorization *************
    131             string authorization = algorithm + " "
    132                 + "Credential=" + secretid + "/" + credentialScope + ", "
    133                 + "SignedHeaders=" + signedHeaders + ", "
    134                 + "Signature=" + signature;
    135             Console.WriteLine(authorization);
    136             Console.WriteLine("----------------------------------");
    137 
    138             Dictionary<string, string> headers = new Dictionary<string, string>();
    139             headers.Add("Authorization", authorization);
    140             headers.Add("Host", endpoint);
    141             headers.Add("Content-Type", contentType + "; charset=utf-8");
    142             headers.Add("X-TC-Timestamp", requestTimestamp.ToString());
    143             headers.Add("X-TC-Version", version);
    144             headers.Add("X-TC-Action", action);
    145             headers.Add("X-TC-Region", region);
    146             return headers;
    147         }
    148     }
    149 }
  • 相关阅读:
    小橙书阅读指南(三)——插入排序
    小橙书阅读指南(二)——选择排序
    小橙书阅读指南(一)——二分查找法
    30分钟带你了解Docker
    消息队列之Kafka——从架构技术重新理解Kafka
    【Mongodb】开启慢查询
    【Azure SQL】数据库性能分析
    【MacBook】常用命令 && 软件安装
    【基准测试】BenchmarkDotNet介绍
    【设计模式】抽象工厂模式
  • 原文地址:https://www.cnblogs.com/shousiji/p/14738348.html
Copyright © 2020-2023  润新知