简体   繁体   English

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

[英]Performing a digital signature using X509Certificate2 prompt for a password to use private key

How can i make sure the C# code uses a password to use the certificate's private key ?我如何确保 C# 代码使用password来使用certificate's private key The certificate is installed in the CurrentUser/Personal store.该证书安装在CurrentUser/Personal存储中。 I tried but still my code uses the private key without prompting for a password.我试过了,但我的代码仍然使用私钥而不提示输入密码。

在此处输入图像描述

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);

When I ran you code with strong key protection enabled I've got an exception Provider could not perform the action since the context was acquired as silent.当我在启用强密钥保护的情况下运行代码时,出现异常Provider could not perform the action since the context was acquired as silent. . . This was because I did not specify the silent parameter in ComputeSignature method and by default it is set to true (so it seems).这是因为我没有在ComputeSignature方法中指定silent参数,默认情况下它设置为true(看起来是这样)。

When you change this line of code当你改变这行代码时

signedCms.ComputeSignature(signer);

to

signedCms.ComputeSignature(signer, false);

then it will prompt for user interaction when necessary ie when you have specified strong key protection in Certificate Import Wizard.然后它会在必要时提示用户交互,即当您在证书导入向导中指定了强密钥保护时。 The documentation can be found here .文档可以在这里找到。

The default action/level of strong private key protection is medium meaning that user will have to approve (click OK) the use of private key.强私钥保护的默认操作/级别为中等,这意味着用户必须批准(单击确定)使用私钥。 You can change it to High protection and set set the password if you want (see screens below).如果需要,您可以将其更改为高保护并设置密码(请参见下面的屏幕)。

设置强私钥保护复选框后

选择保护级别

选定的高级别保护

Is there any solution for this I need to memorize the password, but the program I use it doesn't run all the time when I need it I call the exe,有没有什么解决方案我需要记住密码,但是我使用它的程序在我需要它时并没有一直运行我调用了exe,

to get around this, I had to create a service that runs in the background, that way it works and memorizes, but I need it to be by exe为了解决这个问题,我必须创建一个在后台运行的服务,这样它才能工作和记忆,但我需要它由 exe 执行

PKCS#11 HSM Remember Password PKCS#11 HSM 记住密码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM