MrE*_*yes 4 cryptography export x509certificate2 .net-3.5
我正在尝试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));
Run Code Online (Sandbox Code Playgroud)
当我在最后一行执行时抛出以下异常:
System.Security.Cryptography.CryptographicException
Cannot find the requested object
Run Code Online (Sandbox Code Playgroud)
有谁知道如何解决这个问题?
注意:上面的代码示例是"功能"但它是伪代码.实际上,我将证书导出到一个应用程序中,然后传输到另一个应用程序以进行数字签名(因此只发送公钥)
回答我自己的问题:
问题在于以下行(来自上面的示例):
byte[] arr = exportCertificates[0].PublicKey.EncodedKeyValue.RawData;
Run Code Online (Sandbox Code Playgroud)
这应该是:
byte[] arr = exportCertificates[0].RawData;
Run Code Online (Sandbox Code Playgroud)
这可能看似违反直觉,因为它"似乎"包括整个证书而不仅仅是公钥.但事实并非如此,此更新可根据需要运行.