简体   繁体   中英

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 ? The certificate is installed in the CurrentUser/Personal store. 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. . This was because I did not specify the silent parameter in ComputeSignature method and by default it is set to true (so it seems).

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,

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

PKCS#11 HSM Remember Password

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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