我正在使用C# .NET构建一个文档签名应用程序(Win Form)。在签名过程中,我遇到了一个错误。当我在某些计算机上签署文档(Windows 7、Windows 10,而非Windows Server)时,出现错误:“密钥集未定义”。
请问有人能够提供教程或建议我如何解决这个问题吗?非常感谢!
这是我的代码:
// 获取证书
public X509Certificate2 LoadCertificateFromWindowsStore()
{
X509Store x509Store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
try
{
x509Store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
X509Certificate2Collection numberCerts = (X509Certificate2Collection)x509Store.Certificates;
X509Certificate2Enumerator certEnumerator;
if (numberCerts.Count == 1)
{
certEnumerator = numberCerts.GetEnumerator();
while (certEnumerator.MoveNext())
return certEnumerator.Current;
return null;
}
else if (numberCerts.Count > 1)
{
X509Certificate2Collection chooseCert = X509Certificate2UI.SelectFromCollection(numberCerts,
"Certificates List", "Choose your certificate", X509SelectionFlag.SingleSelection);
if (chooseCert.Count == 1)
return chooseCert[0];
else
return null;
}
else
return null;
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
}
finally
{
x509Store.Close();
}
return null;
}
// 使用证书进行签名
var cert = LoadCertificateFromWindowsStore();
if (cert.HasPrivateKey) // 工作正常!!!
{
signedXml.SigningKey = cert.PrivateKey; // 抛出“密钥集不存在”异常
...