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.

3
  • 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. Commented Jul 17, 2020 at 22:35
  • Does this answer your question? .NET Framework x509Certificate2 Class, HasPrivateKey == true && PrivateKey == null? Commented Jul 17, 2020 at 22:47
  • @bartonjs Kind of? I think, one of the answers did mention using myCert.GetRSAPrivateKey() as per the answer Commented Jul 18, 2020 at 7:10

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.