Skip to content

Commit

Permalink
Constant time string equality
Browse files Browse the repository at this point in the history
  • Loading branch information
jamesseanwright committed Nov 23, 2017
1 parent 322dcc5 commit b1826b4
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions Webhook/RequestValidator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,16 @@

namespace GitHubAutoresponder.Webhook {
public class RequestValidator : IRequestValidator {
private bool AreEqualConstantTime(string a, string b) {
bool areEqual = true;

for (int i = 0; i < a.Length; i++) {
areEqual = areEqual && a[i] == b[i];
}

return areEqual;
}

private string ConvertRawBytesToHexString(byte[] bytes) {
return string.Join(
string.Empty,
Expand All @@ -15,10 +25,10 @@ public bool IsValidRequest(string expectedSignature, string key, string payload)
using (HMACSHA1 hmac = new HMACSHA1(Encoding.ASCII.GetBytes(key))) {
byte[] rawPayload = Encoding.ASCII.GetBytes(payload);
byte[] rawHash = hmac.ComputeHash(rawPayload);
string hash = this.ConvertRawBytesToHexString(rawHash);
string hash = ConvertRawBytesToHexString(rawHash);
string signature = $"sha1={hash}";

return signature == expectedSignature; // TODO: constant-time comparison
return AreEqualConstantTime(signature, expectedSignature);
}
}
}
Expand Down

0 comments on commit b1826b4

Please sign in to comment.