2017-10-16 240 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

相關問題