开发者

.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 anoth开发者_如何学JAVAer 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜