使用X509Certificate2提示执行数字签名以获取密码以使用私钥

时间:2017-10-16 06:13:38

标签: c# x509certificate2

如何确保C#代码使用password来使用certificate's private key?证书安装在CurrentUser/Personal商店中。我尝试了但仍然我的代码使用私钥而没有提示输入密码。

enter image description here

byte[] fileData = File.ReadAllBytes(path);
ContentInfo contentInfo = new ContentInfo(fileData);

SignedCms signedCms = 
new SignedCms(SubjectIdentifierType.SubjectKeyIdentifier, contentInfo, true);
CmsSigner signer = 
new CmsSigner(SubjectIdentifierType.SubjectKeyIdentifier, MyLoadedCert);
signer.IncludeOption = X509IncludeOption.WholeChain;
signedCms.ComputeSignature(signer); // Works fine without prompting password

byte[] encoded = signedCms.Encode();
File.WriteAllBytes(signatureFilePath, encoded);

1 个答案:

答案 0 :(得分:1)

当我运行启用了强密钥保护的代码时,我遇到了异常Provider could not perform the action since the context was acquired as silent.。这是因为我没有在silent方法中指定ComputeSignature参数,默认情况下它设置为true(所以看起来如此)。

更改此行代码时

signedCms.ComputeSignature(signer);

signedCms.ComputeSignature(signer, false);

然后它会在必要时提示用户交互,即在证书导入向导中指定强密钥保护时。可以找到文档here

强私钥保护的默认操作/级别是中等意义,即用户必须批准(单击确定)私钥的使用。您可以将其更改为高防护,并根据需要设置密码(请参阅下面的屏幕)。

After strong private key protection checkbox is set

Choose level of protection

Selected High level of protection