diff --git a/src/API/ApiModule.cs b/src/API/ApiModule.cs index 74df4647c..ad1159ac2 100644 --- a/src/API/ApiModule.cs +++ b/src/API/ApiModule.cs @@ -66,11 +66,12 @@ public static IEndpointRouteBuilder MapApiEndpoints(this IEndpointRouteBuilder b /// Returns a containing a hexadecimal representation of the specified of bytes. /// /// The buffer to generate the hash string for. + /// Whether to return the hash in lowercase. /// /// A containing the hexadecimal representation of . /// - private static string BytesToHexString(ReadOnlySpan bytes) - => Convert.ToHexString(bytes); + private static string BytesToHexString(ReadOnlySpan bytes, bool toLower = false) + => toLower ? Convert.ToHexStringLower(bytes) : Convert.ToHexString(bytes); [OpenApiExample] [OpenApiOperation("Gets the current UTC time.", "Gets the current date and time in UTC.")] @@ -170,28 +171,26 @@ private static Ok GetTime(TimeProvider timeProvider) } byte[] buffer = Encoding.UTF8.GetBytes(request.Plaintext ?? string.Empty); - byte[] hash = request.Algorithm.ToUpperInvariant() switch + HashAlgorithmName? hashAlgorithm = request.Algorithm.ToUpperInvariant() switch { -#pragma warning disable CA5350 -#pragma warning disable CA5351 - "MD5" => MD5.HashData(buffer), - "SHA1" => SHA1.HashData(buffer), -#pragma warning restore CA5350 -#pragma warning restore CA5351 - "SHA256" => SHA256.HashData(buffer), - "SHA384" => SHA384.HashData(buffer), - "SHA512" => SHA512.HashData(buffer), - _ => [], + "MD5" => HashAlgorithmName.MD5, + "SHA1" => HashAlgorithmName.SHA1, + "SHA256" => HashAlgorithmName.SHA256, + "SHA384" => HashAlgorithmName.SHA384, + "SHA512" => HashAlgorithmName.SHA512, + _ => null, }; - if (hash.Length == 0) + if (hashAlgorithm is not { } algorithm) { return Results.Extensions.InvalidRequest($"The specified hash algorithm '{request.Algorithm}' is not supported."); } + byte[] hash = CryptographicOperations.HashData(algorithm, buffer); + var result = new HashResponse() { - Hash = formatAsBase64 ? Convert.ToBase64String(hash) : BytesToHexString(hash).ToLowerInvariant(), + Hash = formatAsBase64 ? Convert.ToBase64String(hash) : BytesToHexString(hash, toLower: true), }; return TypedResults.Json(result, ApplicationJsonSerializerContext.Default.HashResponse);