.NET 8.0 - In Linux, RSAOpenSsl.Equals does not return true when comparing an instance with itself
Description
RSAOpenSsl Equals returns false when comparing an instance with itself when running on Linux in a net8.0 project.
Reproduction Steps
var rsa = RSA.Create(); // creates a RSAOpenSsl in Linux
var result = rsa.Equals(rsa);
Expected behavior
The value of result is true.
Actual behavior
The value of result is false.
Regression?
Don't know.
Known Workarounds
If using data structures for storing RSA objects that use EqualityComparer under the hood (such as ConcurrentDictionary<TKey, RSA>), an adapter class implementing IEquatable can be used to wrap the RSA so the equality checks within the data structure can behave as expected.
Configuration
- net8.0
- Azure Linux 3.0
Other information
This was found when trying to use ConcurrentDictionary<TKey, RSA>::AddOrUpdate. The Update path in this code uses an equality check using the old value that is expected to eventually succeed. The bug causes this to never succeed, so the thread gets stuck inside an infinite while loop that keeps retrying the underlying Update and never succeeds.
Tagging subscribers to this area: @dotnet/area-system-security, @bartonjs, @vcsjones See info in area-owners.md if you want to be subscribed.
var rsa = RSA.Create(); // creates a RSAOpenSsl in Linux
This is not returning a "real" instance of RSAOpenSsl. It's returning an internal implementation-detail class called RSAWrapper. You can see this by using RSA.Create().GetType().FullName.
https://github.com/dotnet/runtime/blob/a077234257c13d09e4f180e9e942cfb5beb4ed2f/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSAWrapper.cs#L218
RSAWrapper is always going to delegate Equals to what it wraps, but since you can get what is wrapped out of the RSAWrapper, this is pretty much going to return false every time.
Perhaps it would make sense to get rid of the Equals override so that reference equality works closer to how it normally would.
That said, what does Equals mean to you with RSA? Typically cryptographic primitives in the runtime do not implement equality, and just rely on reference equality (and in this case, it works a little weird because of the wrapper). If you are expecting reference equality to work, perhaps that is reasonable. But if you are expecting it to compare actual key material, then your workaround sounds like the more suitable solution.
If we want to fix the reference equality, one solution is to simply remove the override bool Equals on the wrapper and let the default reference equality check kick in.
A maybe "more right" solution is to change it to:
public override bool Equals(object? obj) => obj is RSAWrapper wrapper && _wrapped.Equals(wrapper._wrapped);
Thanks for the quick fix!