Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ensure that headers are correctly cased before signature verification… #59

Merged
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
29 changes: 27 additions & 2 deletions BunqSdk/Security/SecurityUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.Security;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using Bunq.Sdk.Context;
using Bunq.Sdk.Exception;
using Bunq.Sdk.Http;
Expand Down Expand Up @@ -78,6 +79,16 @@ public class SecurityUtils
/// </summary>
private const int INDEX_FIRST = 0;

/// <summary>
/// The index after the firts character in a string.
/// </summary>
private const int INDEX_LAST_FIRST_CHAR = 1;

/// <summary>
/// Regex constants.
/// </summary>
private const string REGEX_FOR_LOWERCASE_HEADERS = "(-[a-z])";

/// <summary>
/// Generates a base64-representation of RSA/SHA256/PKCS1 signature for a given RequestMessage.
/// </summary>
Expand Down Expand Up @@ -127,6 +138,20 @@ private static string GenerateRequestHeadersSortedString(HttpRequestMessage requ
);
}

private static string GetHeaderNameCorrectlyCased(string headerName)
{
headerName = headerName.ToLower();
headerName = headerName.First().ToString().ToUpper() + headerName.Substring(INDEX_LAST_FIRST_CHAR);
var matches = Regex.Matches(headerName, REGEX_FOR_LOWERCASE_HEADERS);

return matches.Cast<Match>().Aggregate(
headerName,
(current, match) => current.Replace(
match.Groups[INDEX_FIRST].Value, match.Groups[INDEX_FIRST].Value.ToUpper()
)
);
}

private static string GenerateHeadersSortedString(
IEnumerable<KeyValuePair<string, IEnumerable<string>>> headers)
{
Expand Down Expand Up @@ -307,8 +332,8 @@ private static string GenerateResponseHeadersSortedString(HttpResponseMessage re
{
return GenerateHeadersSortedString(
responseMessage.Headers.Where(x =>
x.Key.StartsWith(HEADER_NAME_PREFIX_X_BUNQ) &&
!x.Key.Equals(HEADER_SERVER_SIGNATURE)
GetHeaderNameCorrectlyCased(x.Key).StartsWith(HEADER_NAME_PREFIX_X_BUNQ) &&
!GetHeaderNameCorrectlyCased(x.Key).Equals(HEADER_SERVER_SIGNATURE)
)
);
}
Expand Down