Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove byte[] allocation in VerifyRsa / VerifyECDsa #2589

Merged
merged 2 commits into from
May 13, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions src/Microsoft.IdentityModel.Tokens/AsymmetricAdapter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
// Licensed under the MIT License.

using System;
#if NET6_0_OR_GREATER
using System.Buffers;
using System.Diagnostics;
#endif
using System.Security.Cryptography;
using Microsoft.IdentityModel.Logging;

Expand Down Expand Up @@ -330,12 +334,20 @@ private static bool VerifyUsingOffsetNotFound(byte[] bytes, int offset, int coun

private bool VerifyECDsa(byte[] bytes, byte[] signature)
{
#if NET6_0_OR_GREATER
return VerifyUsingSpan(isRSA: false, bytes, signature);
#else
return ECDsa.VerifyHash(HashAlgorithm.ComputeHash(bytes), signature);
#endif
}

private bool VerifyUsingOffsetECDsa(byte[] bytes, int offset, int count, byte[] signature)
{
#if NET6_0_OR_GREATER
return VerifyUsingSpan(isRSA: false, bytes.AsSpan(offset, count), signature);
#else
return ECDsa.VerifyHash(HashAlgorithm.ComputeHash(bytes, offset, count), signature);
#endif
}

private byte[] DecryptWithRsa(byte[] bytes)
Expand Down Expand Up @@ -373,14 +385,49 @@ private byte[] SignUsingOffsetRsa(byte[] bytes, int offset, int count)

private bool VerifyRsa(byte[] bytes, byte[] signature)
{
#if NET6_0_OR_GREATER
return VerifyUsingSpan(isRSA: true, bytes, signature);
#else
return RSA.VerifyHash(HashAlgorithm.ComputeHash(bytes), signature, HashAlgorithmName, RSASignaturePadding);
#endif
}

private bool VerifyUsingOffsetRsa(byte[] bytes, int offset, int count, byte[] signature)
{
#if NET6_0_OR_GREATER
return VerifyUsingSpan(isRSA: true, bytes.AsSpan(offset, count), signature);
#else
return RSA.VerifyHash(HashAlgorithm.ComputeHash(bytes, offset, count), signature, HashAlgorithmName, RSASignaturePadding);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since you already have the HashAlgorithmName, why not just call VerifyData and let the framework do the hashing for you (which won't create a temporary array)?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

and let the framework do the hashing for you (which won't create a temporary array)?

This doesn't appear to be the case. When I step into it, I get:

https://github.com/dotnet/runtime/blob/9926d609dab5929941b7924a04521ea2c2df27f3/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSA.cs#L661-L662

Which allocates the byte[].

Here is my test code (on windows):

using System.Security.Cryptography;

RSA rSA = RSA.Create();

byte[] data = [0x1, 0x2, 0x3, 0x4];

byte[] signature = rSA.SignData(data, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);

for (int i = 0; i < 1_000; i++)
{
    rSA.VerifyData(data, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
}

image

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should I submit a similar PR to RSA and ECDsa in dotnet/runtime?

Copy link

@bartonjs bartonjs May 9, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like VerifyData(ReadOnlySpan) uses span-hashing, but VerifyData(byte[]) uses array-hashing; because we never override public virtual bool VerifyData(byte[], int, int, byte[], HashAlgorithmName, RSASignaturePadding). So the change in dotnet/runtime to make everyone happier is probably to override that method on all N of our RSA types. (RSACryptoServiceProvider, RSACng, RSAOpenSsl, RSASecurityTransforms, RSAAndroid, and maybe up to double that from the "RSA.Create()" types). Which is going to involve a lot of copy/paste of the argument validation. Bleh.

Here, though, it means

return rsa.VerifyData(
#if NET5_OR_GREATER
    bytes.AsSpan(offset, count),
#else
    bytes, offset, count,
#endif
    signature,
    HashAlgorithmName,
    RSASignaturePadding);

should take your numbers down to 0 (for .NET5+)

Copy link
Contributor Author

@eerhardt eerhardt May 9, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

RSA is still allocating here:

https://github.com/dotnet/runtime/blob/9926d609dab5929941b7924a04521ea2c2df27f3/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSA.cs#L322

image

HashData returns a new byte[].

Test Code:

using System.Security.Cryptography;

RSA algo = RSA.Create();

byte[] data = [0x1, 0x2, 0x3, 0x4];

byte[] signature = algo.SignData(data, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);

for (int i = 0; i < 1_000; i++)
{
    algo.VerifyData(data.AsSpan(), signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
}

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Weird, since it should have hit the if (this is IRuntimeAlgorithm) above and bypassed the allocation routine. Must've missed a marker interface somewhere, too.

Copy link
Contributor Author

@eerhardt eerhardt May 10, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#endif
}

#if NET6_0_OR_GREATER
private bool VerifyUsingSpan(bool isRSA, ReadOnlySpan<byte> bytes, byte[] signature)
{
int hashByteLength = HashAlgorithm.HashSize / 8;
byte[] array = null;
Span<byte> hash = hashByteLength <= 256 ? stackalloc byte[256] : array = ArrayPool<byte>.Shared.Rent(hashByteLength);
hash = hash.Slice(0, hashByteLength);

try
{
bool hashResult = HashAlgorithm.TryComputeHash(bytes, hash, out int bytesWritten);
Debug.Assert(hashResult && bytesWritten == hashByteLength, "HashAlgorithm.TryComputeHash failed");

return isRSA ?
RSA.VerifyHash(hash, signature, HashAlgorithmName, RSASignaturePadding) :
ECDsa.VerifyHash(hash, signature);
}
finally
{
if (array is not null)
{
ArrayPool<byte>.Shared.Return(array, clearArray: true);
}
}
}
#endif

#region DESKTOP related code
#if DESKTOP
internal byte[] DecryptWithRsaCryptoServiceProviderProxy(byte[] bytes)
Expand Down
Loading