C# 怎样用secrectkey 进行HMACSHA1加密?

新手上路,请多包涵

HMACSHA1 sha1 = HMACSHA1.Create() as HMACSHA1;
sha1.Key = encode.GetBytes(secretKey);//这样用secretkey不对

byte[] encodedPutPolicy = sha1.ComputeHash(encode.GetBytes(encodedPutPolicy ));
string sign = BitConverter.ToString(encodedPutPolicy).Replace("-","").ToLower();
sign = Convert.ToBase64String(encode.GetBytes(sign));

阅读 7.4k
1 个回答

我是服务端代码,我在校验callback安全性的时候遇到类似问题。参考了qiniu csharp-sdk中的源代码,下面是我的代码,你可以参考一下。
另外,看你好像是要做上传凭据生成,用qiniu csharp-sdk就可以了啊

byte[] key = System.Text.Encoding.UTF8.GetBytes(Qiniu.Conf.Config.SECRET_KEY);
using (HMACSHA1 hmac = new HMACSHA1(key))
{
    var t = filterContext.Request.Content.ReadAsStringAsync();
    t.Wait();
    string rawbody = t.Result;
    log.DebugFormat("request's rawbody : {0}", rawbody);
    string text = filterContext.Request.RequestUri.PathAndQuery + "\n" + rawbody;
    log.DebugFormat("PathAndQuery + \\n + rawbody : {0}", text);
    byte[] digest = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(text));
    string computed = Qiniu.Util.Base64URLSafe.Encode(digest);
    log.DebugFormat("Computed hash after base64 : {0}", computed);

    IEnumerable<string> auths;
    if (filterContext.Request.Headers.TryGetValues("Authorization", out auths) && auths.Count() == 1)
    {
        string auth = auths.First();
        log.DebugFormat("Authorization in header : {0}", auth);
        if (auth.StartsWith("QBox "))
        {
            var arr = auth.Substring(5).Split(':');
            if (arr.Length == 2)
            {
                if (arr[1] != computed)
                {
                    log.ErrorFormat("Authorization failed. Since auth from header {0} not equals computed {1}", arr[1], computed);
                }
                else
                {
                    log.Debug("Authorization success.");
                    //only pass can be return
                    return;
                }
            }
            else
            {
                log.Error("Callback Authorization's format is invalid, can not find two part after split by ':'.");
            }
        }
        else
        {
            log.Error("Callback Authorization's format is invalid, missing leading 'QBox '.");
        }
    }
    else
    {
        log.Error("The request from qiniu callback is missing 'Authorization'");
    }

    filterContext.Response = filterContext.Request.CreateResponse(System.Net.HttpStatusCode.Forbidden);

}

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进