Search code examples
c#upgrade.net-5.net-standard-2.0rsacryptoserviceprovider

RSACryptoServiceProvider.VerifyData always returns false in .Net5.0


I am currently migrating some libraries from .netstandard2.0 to .net5.0 and stumbled upon a strange behavior that I cannot really understand, i.e. it worked correctly in .netstandard2.0, but not anymore in .net5.0. I've never worked with any cryptographic code before, so I might miss some obvious point.

I was able to break my problem down to the following:

var cpParams = new CspParameters { KeyContainerName = KEY_CONTAINER };
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cspParams);
rsa.ImportCspBlob(...);
byte[] signature = rsa.SignData(byteArray, new SHA1CryptoServiceProvider());
var isValid = rsa.VerifyData(byteArray, new SHA1CryptoServiceProvider(), signature)

isValid should obviously be true, which we could also verify in .netstandard2.0.

However, after migration to .net5.0, isValid is false.

I did some research, but could not find any explanation on this.

Does anyone have some more insight into this?


Solution

  • I had a similar issue. CspParameters initializes KeyNumber to -1 and, later, ImportCspBlob changed the KeyNumber property from 2 to 1, for whatever reason.

    Try setting the following, and ImportCspBlob will behave.

    CspParameters.KeyNumber = (int)KeyNumber.Signature