此文帮助初次接触COS产品的朋友们,实现快速封装API签名的方法。当然,建议无特殊需求的话,还是要优先考虑COS SDK

COS API,没有读过的朋友请先花半个小时的时间仔细阅读,了解逻辑和方法。

我们直接跳入代码部分,本次的调试环境为VS2015 Framework4.5 C#

//1.参数定义
string SecretId = "这里输入您的SecretId";//SecretId替换成自己的
string SecretKey = "这里输入您的SecretKey";//SecretKey替换成自己的

string domain = "http://{bucket}-{appid}.cos.ap-beijing.myqcloud.com";//把{bucket}  {appid} 都替换成自己的
string q_sign_algorithm = "sha1";
string q_ak = SecretId;
string q_sign_time = GetTimeStamp(DateTime.UtcNow) +";"+ GetTimeStamp(DateTime.UtcNow.AddHours(1));//签名有效期1个小时
string q_key_time = GetTimeStamp(DateTime.UtcNow) + ";" + GetTimeStamp(DateTime.UtcNow.AddHours(1));//签名有效期1个小时;
string q_header_list = "";
string q_url_param_list = "";
string q_signature = "";

string key = "/1.jpg";//uri,这里要确保您的bucket根目录有一个名为1.jpg的对象,也可以修改为别的存在的对象
string method = "get";//请求方式

//2.签名计算
string SignKey = ComputeHash(Encoding.ASCII.GetBytes(SecretKey), q_key_time);//对签名的有效起止时间加密计算值SignKey
string HttpString = method+"\n" + key + "\n\n\n";//根据固定格式组合生成
string StringToSign = q_sign_algorithm+"\n"+ q_sign_time + "\n"+ GetSH1(HttpString) + "\n";//加密 HttpString,并根据固定格式组合生成 StringToSign
string Signature = ComputeHash(Encoding.ASCII.GetBytes(SignKey), StringToSign);//加密 StringToSign,生成 Signature

//3.输出签名后的访问url
Response.Write(domain + key+ "?q-sign-algorithm="+ q_sign_algorithm + "&q-ak="+ q_ak + "&q-sign-time="+ q_sign_time + "&q-key-time="+ q_key_time + "&q-header-list=&q-url-param-list=&q-signature="+ Signature);

//4.工具方法
/// <summary>
/// 获取时间戳
/// </summary>
/// <returns></returns>
public static string GetTimeStamp(DateTime dt)
{
    TimeSpan ts = dt - new DateTime(1970, 1, 1, 0, 0, 0, 0);
    return Convert.ToInt64(ts.TotalSeconds).ToString();
}
/// <summary>
/// 计算哈希
/// </summary>
/// <param name="key"></param>
/// <param name="input"></param>
/// <returns></returns>
public static string ComputeHash(byte[] key, string input)
{
     HMACSHA1 myhmacsha1 = new HMACSHA1(key);
     byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(input);
     MemoryStream stream = new MemoryStream(byteArray);
     return myhmacsha1.ComputeHash(stream).Aggregate("", (s, e) => s + String.Format("{0:x2}", e), s => s);
}
/// <summary>
/// SHA1
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string GetSH1(string value)
{
     SHA1 algorithm = SHA1.Create();
     byte[] data = algorithm.ComputeHash(Encoding.UTF8.GetBytes(value));
     string sh1 = "";
     for (int i = 0; i < data.Length; i++)
     {
                sh1 += data[i].ToString("x2").ToLower();
     }
     return sh1;
}

这样执行完成后会得到例如

http://sunweitest-xxx.cos.ap-beijing.myqcloud.com/1.jpg?q-sign-algorithm=sha1&q-ak=AKIDjNskW7UnqiO3aSLm9KKD0b1Rr8DQIP8k&q-sign-time=1543979817;1543983417&q-key-time=1543979817;1543983417&q-header-list=&q-url-param-list=&q-signature=636ee49f80fd1127dcb8ccd8f70a18f2c2c63b24

的签名url,直接访问即可获取对象。

访问对象

以下是原始代码

#GetsignTest.aspx.zip#

文章来源于腾讯云开发者社区,点击查看原文