How To: Sign a PDF File with a Certificate Stored in the Windows Certificate Store
- 3 minutes to read
The PDF Document API allows you to sign PDF files with certificates (X.509) and digital signatures (PKCS#7). For example, you can sign documents with certificates stored in the Windows Certificate Store.
The following code snippet executes the following actions:
Creates a PKCS#7 signature with the
localhost
certificate stored in the Windows Certificate Store.Note: this certificate is intended for demonstration purposes only. In a production environment, use a trusted certificate issued by a recognized Certificate Authority (CA).
Applies a digital signature to a form field.
- Signs a document with that signature.
using System;
using System.IO;
using System.Linq;
using DevExpress.Office.DigitalSignatures;
using DevExpress.Office.Tsp;
using DevExpress.Pdf;
using System.Security.Cryptography.X509Certificates;
using (var signer = new PdfDocumentSigner("Document.pdf")) {
//Specify the name and location of the signature field
var signatureFieldInfo = new PdfSignatureFieldInfo(1);
signatureFieldInfo.Name = "SignatureField";
signatureFieldInfo.SignatureBounds = new PdfRectangle(20, 20, 150, 150);
signatureFieldInfo.RotationAngle = PdfAcroFormFieldRotation.Rotate90;
//Create a timestamp
ITsaClient tsaClient = new TsaClient(new Uri(@"https://freetsa.org/tsr"), HashAlgorithmType.SHA256);
string certificateSubjectName = "localhost";
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
// Search the certificate by the Subject Name
var storeCertificate = store.Certificates
.Find(X509FindType.FindBySubjectName, certificateSubjectName, validOnly: false)
.OfType<X509Certificate2>()
.FirstOrDefault();
store.Close();
if(storeCertificate == null)
Console.WriteLine($"Certificate with subject name '{certificateSubjectName}' not found.");
else {
Pkcs7Signer pkcs7StoreSignature = new Pkcs7Signer(
storeCertificate, HashAlgorithmType.SHA256, tsaClient, null, null, PdfSignatureProfile.PAdES_BES);
//Apply a signature to a new form field created before
PdfSignatureBuilder storeSignature = new PdfSignatureBuilder(pkcs7StoreSignature, signatureFieldInfo) {
Location = "USA",
Reason = "Acknowledgement",
Name = "Jane Cooper"
};
storeSignature.SetImageData(System.IO.File.ReadAllBytes("Signing Documents/JaneCooper.jpg"));
//Sign and save the document
signer.SaveDocument("SignedDocument.pdf", storeSignature);
}
}
See Also