C#调用腾讯云文本翻译API,使用V3签名报错。

2021-09-22 11:09:58 浏览数 (1)

错误信息:

"Error":{"Code":"AuthFailure.SignatureFailure","Message":"The provided credentials could not be validated. Please check your signature is correct."

签名及POST代码如下:

using Newtonsoft.Json;

using Newtonsoft.Json.Linq;

using System;

using System.Collections.Generic;

using System.IO;

using System.Net;

using System.Security.Cryptography;

using System.Text;

using System.Web.Script.Serialization;

using System.Windows.Forms;

namespace TengXunCloudAPI

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

private Dictionary<string, string> GetSign()

{

// 密钥参数

string SECRET_ID = textBox1.Text;

string SECRET_KEY = textBox2.Text;

string service = "tmt";

string endpoint = "tmt.tencentcloudapi.com";

string region = "ap-chengdu";

string action = "TextTranslate";

string version = "2018-03-21";

string algorithm = "TC3-HMAC-SHA256";

string contentType = "application/json";

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

DateTime date = DateTime.UtcNow;

//DateTime date = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(1632109194);

string datestr = date.ToString("yyyy-MM-dd");

DateTime startTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);

long requestTimestamp = (long)Math.Round((date - startTime).TotalMilliseconds, MidpointRounding.AwayFromZero) / 1000;

// ************* 步骤 1:拼接规范请求串 *************

string httpRequestMethod = "POST";

string canonicalUri = "/";

string canonicalQueryString = "";

string canonicalHeaders = "content-type:" contentType "; charset=utf-8n" "host:" endpoint "n";

string signedHeaders = "content-type;host";

string hashedRequestPayload = SHA256Hex(requestPayload);

string canonicalRequest = httpRequestMethod "n"

canonicalUri "n"

canonicalQueryString "n"

canonicalHeaders "n"

signedHeaders "n"

hashedRequestPayload;

Console.WriteLine(canonicalRequest);

// ************* 步骤 2:拼接待签名字符串 *************

string credentialScope = datestr "/" service "/" "tc3_request";

string hashedCanonicalRequest = SHA256Hex(canonicalRequest);

string stringToSign = algorithm "n" requestTimestamp.ToString() "n" credentialScope "n" hashedCanonicalRequest;

Console.WriteLine(stringToSign);

// ************* 步骤 3:计算签名 *************

byte[] tc3SecretKey = Encoding.UTF8.GetBytes("TC3" SECRET_KEY);

byte[] secretDate = HmacSHA256(tc3SecretKey, Encoding.UTF8.GetBytes(datestr));

byte[] secretService = HmacSHA256(secretDate, Encoding.UTF8.GetBytes(service));

byte[] secretSigning = HmacSHA256(secretService, Encoding.UTF8.GetBytes("tc3_request"));

byte[] signatureBytes = HmacSHA256(secretSigning, Encoding.UTF8.GetBytes(stringToSign));

string signature = BitConverter.ToString(signatureBytes).Replace("-", "").ToLower();

Console.WriteLine(signature);

// ************* 步骤 4:拼接 Authorization *************

string authorization = algorithm " "

"Credential=" SECRET_ID "/" credentialScope ", "

"SignedHeaders=" signedHeaders ", "

"Signature=" signature;

Console.WriteLine(authorization);

Dictionary<string, string> headers = new Dictionary<string, string>();

headers.Add("Authorization", authorization);

//headers.Add("Host", endpoint);

//headers.Add("Content-Type", contentType "; charset=utf-8");

headers.Add("X-TC-Timestamp", requestTimestamp.ToString());

headers.Add("X-TC-Version", version);

headers.Add("X-TC-Action", action);

headers.Add("X-TC-Region", region);

return headers;

}

private Dictionary<string, string> GetParameters()

{

Dictionary<string, string> parameters = new Dictionary<string, string>();

parameters.Add("Action", "TextTranslate");

parameters.Add("ProjectId", "0");

parameters.Add("Source", "zh");

parameters.Add("SourceText", Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(textBox3.Text)));

parameters.Add("Target", "en");

parameters.Add("Version", "2018-03-21");

parameters.Add("Region", "ap-chengdu");

return parameters;

}

private string Post(string url, Dictionary<string, string> headerdatas)

{

try

{

Dictionary<string, string> parameters = GetParameters();

string result = "";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

request.Method = "POST";

request.ContentType = "application/json";

foreach (var data in headerdatas)

{

request.Headers.Add(data.Key, data.Value);

}

StringBuilder builder = new StringBuilder();

int i = 0;

foreach (var item in parameters)

{

if (i > 0)

builder.Append("&");

builder.AppendFormat("{0}={1}", item.Key, item.Value);

i ;

}

string jsonStr = new JavaScriptSerializer().Serialize(builder);

var temp = Encoding.UTF8.GetBytes(jsonStr.ToString());

request.ContentLength = temp.Length;

using (var stream = request.GetRequestStream())

{

stream.Write(temp, 0, temp.Length);

}

var response = (HttpWebResponse)request.GetResponse();

using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))

{

result = reader.ReadToEnd();

}

if (result != "")

{

JObject jo = (JObject)JsonConvert.DeserializeObject(result);

String errorCode = jo["ret"].ToString();

if (errorCode == "0")

{

String dataJObject = jo["data"].ToString();

JObject dataResult = (JObject)JsonConvert.DeserializeObject(dataJObject);

string translateResult = dataResult["target_text"].ToString();

return translateResult;

}

return "参数错误,请检查设置!";

}

return "Error";

}

catch (Exception ex)

{

return ex.Message;

}

}

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);

}

}

private void button1_Click(object sender, EventArgs e)

{

Post("https://tmt.tencentcloudapi.com", GetSign());

}

}

}

调整了好多参数都未能成功,贴出来请教下大家,帮忙给看看是哪里出了问题。小弟在此先谢过了!

0 人点赞