@@ -110,30 +110,26 @@ public IResult GenerateHash(HashRequest request)
110
110
}
111
111
112
112
byte [ ] buffer = Encoding . UTF8 . GetBytes ( request . Plaintext ?? string . Empty ) ;
113
- byte [ ] hash = request . Algorithm . ToUpperInvariant ( ) switch
114
- {
115
- #pragma warning disable CA5350
116
- #pragma warning disable CA5351
117
- "MD5" => MD5 . HashData ( buffer ) ,
118
- "SHA1" => SHA1 . HashData ( buffer ) ,
119
- #pragma warning restore CA5350
120
- #pragma warning restore CA5351
121
- "SHA256" => SHA256 . HashData ( buffer ) ,
122
- "SHA384" => SHA384 . HashData ( buffer ) ,
123
- "SHA512" => SHA512 . HashData ( buffer ) ,
124
- _ => [ ] ,
113
+ HashAlgorithmName ? hashAlgorithm = request . Algorithm . ToUpperInvariant ( ) switch
114
+ {
115
+ "MD5" => HashAlgorithmName . MD5 ,
116
+ "SHA1" => HashAlgorithmName . SHA1 ,
117
+ "SHA256" => HashAlgorithmName . SHA256 ,
118
+ "SHA384" => HashAlgorithmName . SHA384 ,
119
+ "SHA512" => HashAlgorithmName . SHA512 ,
120
+ _ => null ,
125
121
} ;
126
122
127
- if ( hash . Length == 0 )
123
+ if ( hashAlgorithm is not { } algorithm )
128
124
{
129
125
return BadRequest ( $ "The specified hash algorithm '{ request . Algorithm } ' is not supported.") ;
130
126
}
131
127
128
+ byte [ ] hash = CryptographicOperations . HashData ( algorithm , buffer ) ;
129
+
132
130
var result = new HashResponse ( )
133
131
{
134
- #pragma warning disable CA1308
135
- Hash = formatAsBase64 ? Convert . ToBase64String ( hash ) : BytesToHexString ( hash ) . ToLowerInvariant ( ) ,
136
- #pragma warning restore CA1308
132
+ Hash = formatAsBase64 ? Convert . ToBase64String ( hash ) : BytesToHexString ( hash , toLower : true ) ,
137
133
} ;
138
134
139
135
return Results . Json ( result , ApplicationJsonSerializerContext . Default . HashResponse ) ;
@@ -175,14 +171,15 @@ public IResult GenerateMachineKey(string? decryptionAlgorithm, string? validatio
175
171
}
176
172
177
173
/// <summary>
178
- /// Returns a <see cref="string"/> containing a hexadecimal representation of the specified <see cref="Array "/> of bytes.
174
+ /// Returns a <see cref="string"/> containing a hexadecimal representation of the specified <see cref="ReadOnlySpan{T} "/> of bytes.
179
175
/// </summary>
180
176
/// <param name="bytes">The buffer to generate the hash string for.</param>
177
+ /// <param name="toLower">Whether to return the hash in lowercase.</param>
181
178
/// <returns>
182
179
/// A <see cref="string"/> containing the hexadecimal representation of <paramref name="bytes"/>.
183
180
/// </returns>
184
- private static string BytesToHexString ( ReadOnlySpan < byte > bytes )
185
- => Convert . ToHexString ( bytes ) ;
181
+ private static string BytesToHexString ( ReadOnlySpan < byte > bytes , bool toLower = false )
182
+ => toLower ? Convert . ToHexStringLower ( bytes ) : Convert . ToHexString ( bytes ) ;
186
183
187
184
/// <summary>
188
185
/// Returns a result that represents a bad API request.
0 commit comments