Skip to content

Analyzer / fixer proposal: Prefer static HashData methods over ComputeHash #40579

@GrabYourPitchforks

Description

@GrabYourPitchforks

Category: performance, improved linker trimming efficiency (is that even a category?)

We should consider an analyzer that can detect this pattern:

byte[] buffer = GetSomeBuffer();
using (var sha256 = SHA256.Create())
{
    byte[] digest = sha256.ComputeHash(buffer);
    /* use 'digest' here */
}

And suggest the code instead use this pattern:

byte[] buffer = GetSomeBuffer();
byte[] digest = SHA256.HashData(buffer);
/* use 'digest' here */

Using one-shot hashing APIs like this is a bit more foolproof than using the normal stateful instance members on these types.

The analyzer should detect the pattern where a HashAlgorithm instance is created (either via SHA256.Create, new SHA256Managed, or new SHA256CryptoServiceProvider; or via the MD5 / SHA* equivalents), there is a single call made to HashAlgorithm.ComputeHash(byte[]), then there is an optional call made to Dispose.

The analyzer should only trigger for projects targeting net5.0+, as that's when the new static APIs were introduced.

See also: #17590, dotnet/aspnetcore#24696, dotnet/wpf#3318

Metadata

Metadata

Assignees

Labels

api-approvedAPI was approved in API review, it can be implementedarea-System.Securitycode-analyzerMarks an issue that suggests a Roslyn analyzercode-fixerMarks an issue that suggests a Roslyn code fixer

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions