I need to get the public key associated with a certificate..
The code which I found was as follows...

// The path to the certificate.
string Certificate = "Certificate.cer";

// Load the certificate into an X509Certificate object.
X509Certificate cert = X509Certificate.CreateFromCertFile(Certificate);

// Get the value.
byte[] results = cert.GetPublicKey();

Now the problem is that My certificate is stored in the registry..
How will I give the path to the certificate... Plz help....
I am working on windows server 2008...

When you say "registry", do you mean the actual registry, or the certificate store (accessed by running "mmc", then from the "File" menu, selecting "Add/Remove Snap-in...", then selecting the "Certificates" snap-in, etc.)? If the latter, see below...

It's been a bit, but I used this code in the past to pick a certificate out of the certificate store:

using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
X509Store store = new X509Store(StoreLocation.LocalMachine);
X509CertificateCollection certs = store.Certificates.Find(X509FindType.FindSubjectByName, "XXX", true);

"certs" will contain a list of certificates that match the find type, in this case, if the subject in the certificate is "XXX".

To extract the first certificate in the collection, you can do:

X509Certificate2 cert = ((X509Certificate2)certs[0]);

This worked on Windows Server 2003. Also, you can change where in the certificate store you're looking by changing the "StoreLocation" when creating the "store" variable.

Good luck!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.