2017-10-16 236 views
1

如何确保C#代码使用password来使用certificate's private key?证书安装在CurrentUser/Personal商店中。我试过,但仍然我的代码使用私钥而不提示输入密码。使用X509Certificate2执行数字签名提示输入密码以使用私钥

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

当我跑到你的代码与强密钥保护启用我有一个例外Provider could not perform the action since the context was acquired as silent.。这是因为我没有在ComputeSignature方法中指定silent参数,并且默认情况下它被设置为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

+0

它不抛出任何为我破例。但是如果我把'signedCms.ComputeSignature(signer,false)',那么它会在外部窗口中提示输入密码。为什么在静音模式下它不起作用?我的证书中是否需要某些东西? –

+0

@GokulE它是恕我直言静默模式=不允许用户交互。我没有在.NET中找到任何方式来检查一个证书是否具有强大的密钥保护,但也许我只是 看起来不够硬:) – pepo

相关问题