diff --git a/WebApiThrottle/ThrottlingCore.cs b/WebApiThrottle/ThrottlingCore.cs index a179792..61b57d3 100644 --- a/WebApiThrottle/ThrottlingCore.cs +++ b/WebApiThrottle/ThrottlingCore.cs @@ -1,8 +1,10 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Net; using System.Net.Http; +using System.Security.Cryptography; using System.Text; using WebApiThrottle.Net; @@ -118,40 +120,37 @@ internal bool IsWhitelisted(RequestIdentity requestIdentity) internal string ComputeThrottleKey(RequestIdentity requestIdentity, RateLimitPeriod period) { - var keyValues = new List() - { - ThrottleManager.GetThrottleKey() - }; - - if (Policy.IpThrottling) + using (var ms = new MemoryStream()) + using (var sw = new StreamWriter(ms, Encoding.UTF8)) { - keyValues.Add(requestIdentity.ClientIp); - } + sw.Write(ThrottleManager.GetThrottleKey()); - if (Policy.ClientThrottling) - { - keyValues.Add(requestIdentity.ClientKey); - } + if (Policy.IpThrottling) + { + sw.Write(requestIdentity.ClientIp); + } - if (Policy.EndpointThrottling) - { - keyValues.Add(requestIdentity.Endpoint); - } + if (Policy.ClientThrottling) + { + sw.Write(requestIdentity.ClientKey); + } - keyValues.Add(period.ToString()); + if (Policy.EndpointThrottling) + { + sw.Write(requestIdentity.Endpoint); + } - var id = string.Join("_", keyValues); - var idBytes = Encoding.UTF8.GetBytes(id); + sw.Write(period); - byte[] hashBytes; + sw.Flush(); - using (var algorithm = System.Security.Cryptography.SHA1.Create()) - { - hashBytes = algorithm.ComputeHash(idBytes); + ms.Position = 0; + using (var algorithm = new SHA1Managed()) + { + var hash = algorithm.ComputeHash(ms); + return Convert.ToBase64String(hash); + } } - - var hex = BitConverter.ToString(hashBytes).Replace("-", string.Empty); - return hex; } internal List> RatesWithDefaults(List> defRates)