From f049706252cb1995efd47d1921a1cc1cb0d36fa8 Mon Sep 17 00:00:00 2001 From: shijiayun Date: Thu, 19 Jul 2012 11:48:21 +0800 Subject: [PATCH] add x-www-form-urlencoded body for digest --- QBox/Client.cs | 8 ++++---- QBox/DigestAuthClient.cs | 21 +++++++++++++++------ 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/QBox/Client.cs b/QBox/Client.cs index d9d39177..8d76dc5b 100755 --- a/QBox/Client.cs +++ b/QBox/Client.cs @@ -6,8 +6,8 @@ namespace QBox { public abstract class Client { - public abstract void SetAuth(HttpWebRequest request); - + public abstract void SetAuth(HttpWebRequest request, byte[] body); + public CallRet Call(string url) { Console.WriteLine("URL: " + url); @@ -15,7 +15,7 @@ public CallRet Call(string url) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; - SetAuth(request); + SetAuth(request, null); using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { return HandleResult(response); @@ -37,7 +37,7 @@ public CallRet CallWithBinary(string url, string contentType, byte[] body) request.Method = "POST"; request.ContentType = contentType; request.ContentLength = body.Length; - SetAuth(request); + SetAuth(request, body); using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(body, 0, body.Length); diff --git a/QBox/DigestAuthClient.cs b/QBox/DigestAuthClient.cs index 518f51ed..f8663575 100755 --- a/QBox/DigestAuthClient.cs +++ b/QBox/DigestAuthClient.cs @@ -8,18 +8,27 @@ namespace QBox { public class DigestAuthClient : Client { - public override void SetAuth(HttpWebRequest request) + public override void SetAuth(HttpWebRequest request, byte[] body) { byte[] secretKey = Encoding.ASCII.GetBytes(Config.SECRET_KEY); using (HMACSHA1 hmac = new HMACSHA1(secretKey)) { string pathAndQuery = request.Address.PathAndQuery; - byte[] bytesIn = Encoding.ASCII.GetBytes(pathAndQuery + "\n"); - byte[] digest = hmac.ComputeHash(bytesIn); - string digestBase64 = Base64UrlSafe.Encode(digest); + byte[] pathAndQueryBytes = Encoding.ASCII.GetBytes(pathAndQuery); + using (MemoryStream buffer = new MemoryStream()) + { + buffer.Write(pathAndQueryBytes, 0, pathAndQueryBytes.Length); + buffer.WriteByte((byte)'\n'); + if (request.ContentType == "application/x-www-form-urlencoded" && body != null) + { + buffer.Write(body, 0, body.Length); + } + byte[] digest = hmac.ComputeHash(buffer.ToArray()); + string digestBase64 = Base64UrlSafe.Encode(digest); - string authHead = "QBox " + Config.ACCESS_KEY + ":" + digestBase64; - request.Headers.Add("Authorization", authHead); + string authHead = "QBox " + Config.ACCESS_KEY + ":" + digestBase64; + request.Headers.Add("Authorization", authHead); + } } } }