diff --git a/src/OidcClient/CryptoHelper.cs b/src/OidcClient/CryptoHelper.cs index 7fde5cb..4366bad 100644 --- a/src/OidcClient/CryptoHelper.cs +++ b/src/OidcClient/CryptoHelper.cs @@ -56,10 +56,10 @@ public bool ValidateHash(string data, string hashedData, string signatureAlgorit using (hashAlgorithm) { var hash = hashAlgorithm.ComputeHash(Encoding.ASCII.GetBytes(data)); - var size = (hashAlgorithm.HashSize / 8) / 2; + var size = hashAlgorithm.HashSize / 8 / 2; // Only take the left half of the data, as per spec for at_hash - byte[] leftPart = new byte[hashAlgorithm.HashSize / size]; - Array.Copy(hash, leftPart, hashAlgorithm.HashSize / size); + byte[] leftPart = new byte[size]; + Array.Copy(hash, leftPart, size); var leftPartB64 = Base64Url.Encode(leftPart); var match = leftPartB64.Equals(hashedData); diff --git a/test/OidcClient.Tests/CryptoHelperTests.cs b/test/OidcClient.Tests/CryptoHelperTests.cs new file mode 100644 index 0000000..d743ba1 --- /dev/null +++ b/test/OidcClient.Tests/CryptoHelperTests.cs @@ -0,0 +1,31 @@ +using System; +using System.Text; +using FluentAssertions; +using IdentityModel; +using IdentityModel.OidcClient; +using Xunit; + +public class CryptoHelperTests +{ + [Theory] + [InlineData("asdf", "RS256")] + [InlineData("asdf", "RS384")] + [InlineData("asdf", "RS512")] + public void ComputeHash_should_compute_correct_hashes_for_all_signature_algorithms(string data, string algorithmName) + { + var sut = new CryptoHelper(new OidcClientOptions()); + var algorithm = sut.GetMatchingHashAlgorithm(algorithmName); + + var hash = algorithm.ComputeHash(Encoding.ASCII.GetBytes(data)); + + var bytesInLeftHalf = algorithm.HashSize / 16; // Divide by 8 for bytes and then 2 to get just half, as per spec for at_hash. + + var leftHalf = new byte[bytesInLeftHalf]; + Array.Copy(hash, leftHalf, bytesInLeftHalf); + + var hashString = Base64Url.Encode(leftHalf); + + sut.ValidateHash(data, hashString, algorithmName).Should().BeTrue(); + } + +} \ No newline at end of file