Y.S
Y.S

Reputation: 1862

Adding a private key to X509Certificate2 - C#

I'm new to 2WaySSL.

What I'm trying to do:

1. Retrieve a Client certificate which is stored in a certificate store,
I'm managing to do that by such code:



 certificates = store.Certificates.Find(X509FindType.FindBySerialNumber, serialNumber, false);

When attaching the certificate to the request, the authentication by the server fails, since I the certificate object does not contain the private key.

I'm trying to find a way of associating the private key to the certificate (in c#), Once I'll retrieve the key from where it's stored.

something like:

   certificate.PrivateKey = key;

But I found no easy way of either initiating the key object, or assigning it to the certificate without getting some exception, even when the key is null, I'm getting an access denied exception.

Any help , especially followed by a code sample, would be appreciated.

Upvotes: 1

Views: 6197

Answers (2)

saravanan
saravanan

Reputation: 408

AFter .NET 4.7.2, If you have the certificate with only public key and an RSA private key handy you can perform the below code

certificate= certificate.CopyWithPrivateKey(key);

you have to import System.Security.Cryptography.X509Certificates;

Upvotes: 2

pepo
pepo

Reputation: 8877

You have 2 easy options

  • import certificate with private key (usually a pfx file) to certificate store. Then store.Certificates.Find will retrieve the certificate with private key.
  • Load pfx file into X509Certificate2 istance with one of its constructors new X509Certificate2(pfx_filename, password_to_pfx)

Upvotes: 0

Related Questions