Automatic PDF Digital Signature (Bypass Certificate PIN dialog) in C#

To digitally sign a PDF using a certificate stored on the smart card or HSM (Hardware Security Module), it must be first installed on Microsoft Certificate Store (MS-CAPI).

In case the digital signature must be made without user intervention (automate the entire digital signature process), the certificate must be selected using a unique criteria.

If the desired certificate has in the Subject field the value E = email@email.com, you can use the following code to automatically use the certificate for the signing operation.

There are a lot of criteria to automatically select your certificate (Common Name, Serial Number, Thumbprint, etc.).

If the certificate is stored on a smart card or USB token, the PIN dialog might be automatically bypassed for some models.

This feature will NOT work for all available smart card/USB tokens because of the drivers or other security measures. Use this property carefully.

In order to bypass the PIN dialog window, DigitalCertificate.SmartCardPin property must be set. The code below, bypass the PIN dialog and the file is automatically signed without any user intervention.

PdfSignature ps = new PdfSignature("");

//load the PDF document
ps.LoadPdfDocument("source.pdf");
ps.SignaturePosition = SignaturePosition.TopRight;
ps.SigningReason = "I approve this document";
ps.SignaturePosition = SignaturePosition.TopLeft;

//load the certificate from Microsoft Certificate Store without user intervention using a criteria
ps.DigitalSignatureCertificate = DigitalCertificate.LoadCertificate(false,
DigitalCertificateSearchCriteria.EmailE, "email@email.com");

//The PIN dialog is now bypassed
DigitalCertificate.SmartCardPin = "123456";

//write the signed file
File.WriteAllBytes("source[signed].pdf", ps.ApplyDigitalSignature());

See also: