2

With C#, I want to be able to Decrypt data using a certificate. However in .NET Core (3.1) I am unable to use the certificate to decrypt. Interestingly, it works fine in .NET Framework (4.8). In .NET Core, I can find and see the certificate, but when I try to cast it to a RSACryptoServiceProvider the result is always NULL. No issues at all in .NET Framework when I do the same thing.

I am creating a certificate using the makecert.exe utility like so:

makecert.exe -r -pe -n "CN=MyCert" -ss my -sr localmachine -eku 1.3.6.1.5.5.7.3.2 -len 2048 -e 01/01/2024 -sky Exchange C:\temp\MyCert.cer

Did something change in .NET Core with regards to certificates? Or am I missing something?

X509Certificate2 myCert = null;
var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
var certCollection = store.Certificates.Find(X509FindType.FindByThumbprint, "72A5303B5CB3EF70BEC360E29FA5E9D86886EA44", false);
if (certCollection.Count == 1)
{
    myCert = certCollection[0];
}
else
{
    return;
}

var rsakey = (RSA)myCert.PrivateKey;
// In .NET Core rsp is always null
var rsp = (RSACryptoServiceProvider)rsakey;

I have tried various other approaches in similar StackOverflow questions, but to no avail.

  • Write some debug messages to a log file to see where the program is going and where its breaking down. Should make for a fairly easy solve. – alexherm Jul 17 '20 at 22:35
  • Does this answer your question? [.NET Framework x509Certificate2 Class, HasPrivateKey == true && PrivateKey == null?](https://stackoverflow.com/questions/36730596/net-framework-x509certificate2-class-hasprivatekey-true-privatekey-nu) – bartonjs Jul 17 '20 at 22:47
  • @bartonjs Kind of? I think, one of the answers did mention using `myCert.GetRSAPrivateKey()` as per the answer – segmentation_fault Jul 18 '20 at 07:10

1 Answers1

3

Ciao, according to MSDN example here to get private key in .NET Core 3.1 you have to call myCert.GetRSAPrivateKey().

Giovanni Esposito
  • 10,696
  • 1
  • 14
  • 30