最近对接腾讯云的API,需要用C#生成Authentication Header的加密字符串,搜索引擎上找不到例子,自己摸索遇到了不少问题,为方便大家现在放出来,都是测试性的代码,逻辑是正确的,如果用于生产环境,你自己优化封装:
var source=GetKeyValueString(); var signature = HMACSha1Bytes(source, _SecretKey); var authorizationValue = System.Convert.ToBase64String(signature.Concat(Encoding.UTF8.GetBytes(source)).ToArray()); static byte[] HMACSha1Bytes(String data, String key) { HMACSHA1 hmacsha1 = new HMACSHA1(); hmacsha1.Key = Encoding.UTF8.GetBytes(key); byte[] dataBuffer = Encoding.UTF8.GetBytes(data); byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer); return hashBytes; } static String GetKeyValueString() { var e = ToUnixTime(DateTime.Now.AddMinutes(10));//可重用的 //var e = 0;//仅一次可用 var t = ToUnixTime(DateTime.Now); var r = new Random().Next(100,1000000); return "a=" + _AppId + "&b=" + _bucket + "&k=" + _SecretId + "&e=" + e.ToString() + "&t=" + t + "&r=" + r.ToString() + "&u=0&f="; } public static long ToUnixTime( DateTime date) { var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); return System.Convert.ToInt64((date - epoch).TotalSeconds); }