Skip to content

Commit

Permalink
Remove hash work in RsaPaddingProcessor.OpenProcessor
Browse files Browse the repository at this point in the history
Remove hash work in RsaPaddingProcessor.OpenProcessor.

This was hashing data to determine the length of the hash. But we know MD5 is always going to be 16, SHA1 is going to be 20, etc. so don't waste any time hashing anything.
  • Loading branch information
vcsjones authored Apr 26, 2022
1 parent 8dec3ce commit e4163ea
Showing 1 changed file with 35 additions and 38 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -76,46 +76,43 @@ internal static RsaPaddingProcessor OpenProcessor(HashAlgorithmName hashAlgorith
hashAlgorithmName,
static hashAlgorithmName =>
{
using (IncrementalHash hasher = IncrementalHash.CreateHash(hashAlgorithmName))
{
// SHA-2-512 is the biggest we expect
Span<byte> stackDest = stackalloc byte[512 / 8];
ReadOnlyMemory<byte> digestInfoPrefix;

if (hashAlgorithmName == HashAlgorithmName.MD5)
{
digestInfoPrefix = s_digestInfoMD5;
}
else if (hashAlgorithmName == HashAlgorithmName.SHA1)
{
digestInfoPrefix = s_digestInfoSha1;
}
else if (hashAlgorithmName == HashAlgorithmName.SHA256)
{
digestInfoPrefix = s_digestInfoSha256;
}
else if (hashAlgorithmName == HashAlgorithmName.SHA384)
{
digestInfoPrefix = s_digestInfoSha384;
}
else if (hashAlgorithmName == HashAlgorithmName.SHA512)
{
digestInfoPrefix = s_digestInfoSha512;
}
else
{
Debug.Fail("Unknown digest algorithm");
throw new CryptographicException();
}
ReadOnlyMemory<byte> digestInfoPrefix;
int digestLength;

if (hasher.TryGetHashAndReset(stackDest, out int bytesWritten))
{
return new RsaPaddingProcessor(hashAlgorithmName, bytesWritten, digestInfoPrefix);
}

byte[] big = hasher.GetHashAndReset();
return new RsaPaddingProcessor(hashAlgorithmName, big.Length, digestInfoPrefix);
if (hashAlgorithmName == HashAlgorithmName.MD5)
{
digestInfoPrefix = s_digestInfoMD5;
#pragma warning disable CA1416 // Unsupported on Browser. We just want the const here.
digestLength = MD5.HashSizeInBytes;
#pragma warning restore CA1416
}
else if (hashAlgorithmName == HashAlgorithmName.SHA1)
{
digestInfoPrefix = s_digestInfoSha1;
digestLength = SHA1.HashSizeInBytes;
}
else if (hashAlgorithmName == HashAlgorithmName.SHA256)
{
digestInfoPrefix = s_digestInfoSha256;
digestLength = SHA256.HashSizeInBytes;
}
else if (hashAlgorithmName == HashAlgorithmName.SHA384)
{
digestInfoPrefix = s_digestInfoSha384;
digestLength = SHA384.HashSizeInBytes;
}
else if (hashAlgorithmName == HashAlgorithmName.SHA512)
{
digestInfoPrefix = s_digestInfoSha512;
digestLength = SHA512.HashSizeInBytes;
}
else
{
Debug.Fail("Unknown digest algorithm");
throw new CryptographicException();
}

return new RsaPaddingProcessor(hashAlgorithmName, digestLength, digestInfoPrefix);
});
}

Expand Down

0 comments on commit e4163ea

Please sign in to comment.