【c#】腾讯人脸识别api签名
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; namespace ConsoleApp1 { class Program { static void Main(string[] args) { String authHost = "https://recognition.image.myqcloud.com/face/compare"; uint rdm = (uint)Math.Abs(new Random().Next()); var sign = AppSign("1251504741", "", ""); HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Host = "recognition.image.myqcloud.com"; client.DefaultRequestHeaders.Add("Authorization", $"Basic {sign}"); var jsArr = new Dictionary<string, object>(); jsArr.Add("appid", "1251504741"); jsArr.Add("urlA", "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1547392505&di=829f4486e205b95c072970acaba924ca&imgtype=jpg&er=1&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201409%2F09%2F20140909220439_myxuV.jpeg"); jsArr.Add("urlB", "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1547392532&di=9dd58cd8356f5e90eda00e53183f1a81&imgtype=jpg&er=1&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201508%2F14%2F20150814165156_iAvkx.jpeg"); HttpContent str = new StringContent(JsonConvert.SerializeObject(jsArr)); str.Headers.Remove("Content-Type"); str.Headers.Add("Content-Type", "application/json"); HttpResponseMessage response = client.PostAsync(authHost, str).Result; String result = response.Content.ReadAsStringAsync().Result; } private static string AppSign(string appId, string secretId, string secretKey) { var ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); var currentTime = Convert.ToInt64(ts.TotalSeconds);//当前时间戳,是一个符合 UNIX Epoch 时间戳规范的数值,单位为秒,多次签名时,e 应大于 t var expiredTime = Convert.ToInt64((DateTime.UtcNow.AddMinutes(180) - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds);//签名的有效期,是一个符合 UNIX Epoch 时间戳规范的数值,单位为秒;单次签名时,e 必须设置为 0 string plainText = $"a={appId}&b=&k={secretId}&e={expiredTime}&t={currentTime}&r={GetRandom()}&f="; return Hmacsha1Encrypt(plainText, secretKey); } /// <summary> /// HMACSHA1算法加密 /// </summary> private static string Hmacsha1Encrypt(string encryptText, string encryptKey) { using (HMACSHA1 mac = new HMACSHA1(Encoding.UTF8.GetBytes(encryptKey))) { var hash = mac.ComputeHash(Encoding.UTF8.GetBytes(encryptText)); var pText = Encoding.UTF8.GetBytes(encryptText); var all = new byte[hash.Length + pText.Length]; Array.Copy(hash, 0, all, 0, hash.Length); Array.Copy(pText, 0, all, hash.Length, pText.Length); return Convert.ToBase64String(all); } } /// <summary> /// 获取随机数 /// </summary> private static int GetRandom() { var random = new Random(); var rand = random.Next(10000, 999999999); return rand; } } }