Skip to content
This repository has been archived by the owner on Nov 1, 2023. It is now read-only.

improve key calculation performance and reduce key size #123

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 25 additions & 26 deletions WebApiThrottle/ThrottlingCore.cs
Original file line number Diff line number Diff line change
@@ -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;

Expand Down Expand Up @@ -118,40 +120,37 @@ internal bool IsWhitelisted(RequestIdentity requestIdentity)

internal string ComputeThrottleKey(RequestIdentity requestIdentity, RateLimitPeriod period)
{
var keyValues = new List<string>()
{
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<KeyValuePair<RateLimitPeriod, long>> RatesWithDefaults(List<KeyValuePair<RateLimitPeriod, long>> defRates)
Expand Down