Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET 3.5 - Export X509Certificate2 PublicKey - Cannot find the requested object

I am attempting to export the public key of an X509Certificate2 certificate using the following code:

X509Store certificateStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
certificateStore.Open(OpenFlags.ReadOnly);
var exportCertificates = certificateStore.Certificates.Find(X509FindType.FindByThumbprint, "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", false);
certificateStore.Close();

// Get Base64 string of the public key
byte[] arr = exportCertificates[0].PublicKey.EncodedKeyValue.RawData;
string b64ExportCertificate = Convert.ToBase64String(arr);

// Import the certificate
X509Certificate2 importCertificate = new X509Certificate2(Convert.FromBase64String(b64ExportCertificate));

When I the last line executes the following exception is thrown:

System.Security.Cryptography.CryptographicException
Cannot find the requested object

Does anybody know how to resolve this?

NOTE : The code sample above is "functional" but it is psuedo code. In reality I am exporting the certificate in one application and then transmitting to another for the purpose of digitial signatures (hence only sending the public key)

like image 626
MrEyes Avatar asked Feb 26 '23 00:02

MrEyes


1 Answers

Answering my own question:

The issue lies with the following line (from the sample above):

byte[] arr = exportCertificates[0].PublicKey.EncodedKeyValue.RawData;

This should be:

byte[] arr = exportCertificates[0].RawData;

This may seem counter intuitive as it "seems" that this would include the entire certificate not just the public key. However this is not the case and this update works as needed.

like image 51
MrEyes Avatar answered Apr 19 '23 23:04

MrEyes