"密钥无法在指定状态下使用"在尝试签署Xml时

时间:2015-08-11 15:45:48

标签: c# xml .net-4.0 x509certificate2

我的历史:

我需要在上传到政府机构之前签署所有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)

它表示getter的{​​{1}}正在抛出该异常。 稍后,我会尝试再次安装该证书,并检查PrivateKey

PS:Exportable

1 个答案:

答案 0 :(得分:1)

由于我的客户更改了密码,因此需要再次安装certificate

就是这样。