Skip to content
This repository has been archived by the owner on Feb 23, 2025. It is now read-only.

Fix at_hash calculation for RS384, RS512 #410

Merged
merged 2 commits into from
Feb 27, 2024
Merged
Show file tree
Hide file tree
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
6 changes: 3 additions & 3 deletions src/OidcClient/CryptoHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
31 changes: 31 additions & 0 deletions test/OidcClient.Tests/CryptoHelperTests.cs
Original file line number Diff line number Diff line change
@@ -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();
}

}
Loading