“密钥在指定状态下无效”;在尝试签署Xml时

本文关键字:Xml 签署 无效 密钥 状态 | 更新日期: 2023-09-27 18:07:23

My History:

我需要在我所有的Xml's上传到政府机构之前签名。要签名,我使用从X509Store加载的客户端证书:

var repo = new X509Store("My", StoreLocation.CurrentUser);
repo.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
foreach (X509Certificate2 certCurrent in repo.Certificates)
{
    if (!certCurrent.Subject.Equals(subject)) continue;
    if (certCurrent.NotAfter > DateTime.Now)
    {
        repo.Close();
        return certCurrent;
    }
}
repo.Close();
return null;

SignedXml (XmlDocument xmlDoc, string id, X509Certificate2 certificate):

var refer = new Reference();
refer.Uri = "#" + id;
refer.AddTransform(new XmlDsigEnvelopedSignatureTransform());
refer.AddTransform(new XmlDsigC14NTransform());
var signedXml = new SignedXml(xmlDoc);
signedXml.SigningKey = certificate.PrivateKey;
signedXml.AddReference(refer);
signedXml.ComputeSignature();
var key = new KeyInfo();
key.AddClause(new KeyInfoX509Data(certificate));
signedXml.KeyInfo = key;
//Final signature xml block.
XmlElement signedBlock = signedXml.GetXml();

问题:

我的一个客户更改了他的PC密码,并且莫名其妙地抛出了第二个代码块错误:

Message - 
    Key not valid for use in specified state.
Type - 
    CryptographicException
Source - 
    mscorlib
TargetSite - 
    System.Security.Cryptography.SafeProvHandle CreateProvHandle(System.Security.Cryptography.CspParameters, Boolean)
StackTrace - 
    at System.Security.Cryptography.Utils.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer)
    at System.Security.Cryptography.Utils.GetKeyPairHelper(CspAlgorithmType keyType, CspParameters parameters, Boolean randomKeyContainer, Int32 dwKeySize, SafeProvHandle& safeProvHandle, SafeKeyHandle& safeKeyHandle)
    at System.Security.Cryptography.RSACryptoServiceProvider.GetKeyPair()
    at System.Security.Cryptography.RSACryptoServiceProvider..ctor(Int32 dwKeySize, CspParameters parameters, Boolean useDefaultKeySize)
    at System.Security.Cryptography.X509Certificates.X509Certificate2.get_PrivateKey()
    at Util.SignXml.Sign(XmlDocument xmlDoc, String id, X509Certificate2 certificate, String& error)

表示PrivateKeygetter抛出异常。稍后,我将尝试再次安装该证书,并选中Exportable

PS: Windows Server 2003

“密钥在指定状态下无效”;在尝试签署Xml时

由于我的客户更改了密码,所以需要重新安装certificate

创建一个新的测试证书似乎解决了这个问题。这篇博文给我指明了正确的方向。

打开给出错误的项目的属性页。单击"签名"选项卡。单击"创建测试证书"。输入密码,单击"确定"。