.NET 3.5 - 导出 X509Certificate2 PublicKey - 找不到请求的对象

发布于 2024-10-18 21:59:55 字数 917 浏览 2 评论 0原文

我正在尝试使用以下代码导出 X509Certificate2 证书的公钥:

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));

当我执行最后一行时,会引发以下异常:

System.Security.Cryptography.CryptographicException
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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烟雨扶苏 2024-10-25 21:59:55

回答我自己的问题:

问题在于以下行(来自上面的示例):

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

这应该是:

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

这可能看起来违反直觉,因为它“似乎”包括整个证书而不仅仅是公钥。但事实并非如此,此更新根据需要起作用。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文