Skip to content

Commit

Permalink
Implementing constant-time comparison in JwtValidator (#111)
Browse files Browse the repository at this point in the history
* Implementing constant-time comparison in JwtValidator
* Bumping nuget version
  • Loading branch information
abatishchev authored May 15, 2017
1 parent 532bb1c commit e0092b8
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/JWT/JWT.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
<PackageProjectUrl>https://github.com/jwt-dotnet/jwt</PackageProjectUrl>
<Authors>John Sheehan, Michael Lehenbauer, Alexander Batishchev</Authors>
<PackageLicenseUrl>https://creativecommons.org/publicdomain/zero/1.0/</PackageLicenseUrl>
<Version>3.0.0-beta3</Version>
<Version>3.0.0-beta4</Version>
<PackageTags>jwt json</PackageTags>
</PropertyGroup>

Expand Down
23 changes: 22 additions & 1 deletion src/JWT/JwtValidator.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Text;

namespace JWT
{
Expand Down Expand Up @@ -31,7 +32,7 @@ public JwtValidator(IJsonSerializer jsonSerializer, IDateTimeProvider dateTimePr
/// <inheritdoc />
public void Validate(string payloadJson, string decodedCrypto, string decodedSignature)
{
if (decodedCrypto != decodedSignature)
if (!CompareCryptoWithSignature(decodedCrypto, decodedSignature))
{
throw new SignatureVerificationException("Invalid signature")
{
Expand Down Expand Up @@ -99,5 +100,25 @@ public void Validate(string payloadJson, string decodedCrypto, string decodedSig
}
}
}

/// <remarks>In the future this method can be open for extension so made protected virtual</remarks>
private static bool CompareCryptoWithSignature(string decodedCrypto, string decodedSignature)
{
if (decodedCrypto.Length != decodedSignature.Length)
{
return false;
}

byte[] decodedCryptoBytes = Encoding.ASCII.GetBytes(decodedCrypto);
byte[] decodedSignatureBytes = Encoding.ASCII.GetBytes(decodedSignature);

byte result = 0;
for (int i = 0; i < decodedCrypto.Length; i++)
{
result |= (byte)(decodedCryptoBytes[i] ^ decodedSignatureBytes[i]);
}

return result == 0;
}
}
}

0 comments on commit e0092b8

Please sign in to comment.