Prefer static HashData method over ComputeHash
Prefer static HashData method over ComputeHash
Microsoft docsDescription
Static HashData methods were introduced in .NET 5 on the following types:
- System.Security.Cryptography.MD5
- System.Security.Cryptography.SHA1
- System.Security.Cryptography.SHA256
- System.Security.Cryptography.SHA384
- System.Security.Cryptography.SHA512
These methods help simplify code in cases where you just want to hash some data.
It's more efficient to use these static HashData methods than to create and manage a HashAlgorithm instance to call ComputeHash.
Cause
An instance of a type that derives from System.Security.Cryptography.HashAlgorithm is created to call its ComputeHash method, and that type has a static HashData method.
How to fix violations
In general, you can fix the rule by changing your code to call HashData and remove use of the HashAlgorithm instance.
The previous code can be changed to call the static System.Security.Cryptography.SHA256.HashData(System.Byte[]) method directly.
Example
public bool CheckHash(byte[] buffer)
{
using (var sha256 = SHA256.Create())
{
byte[] digest = sha256.ComputeHash(buffer);
return DoesHashExist(digest);
}
}When to suppress
It is safe to suppress a warning from this rule.