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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With