SelectPdf for .NET 10 - Digital Signatures - C# / .NET 10 Sample

Digital signatures can be added to a PDF document using PdfDigitalSignatureElement objects. Adding a digital signature requires a PKCS#12 certificate (provided as a .pfx or a .p12 file).

Sample certificate file:
Certificate

The following sample shows how to add a digital signature to a pdf document using SelectPdf Library for .NET.

IMPORTANT: Please note that the certificate used is a self signed certificate generated for testing purposes only. The signature will appear as not valid in a pdf viewer. Using a valid certificate will result in a valid digital signature.

Validate Signatures

PdfSecurityManager.ValidateSignatures checks every signature of a pdf document: whether it is intact, whether its certificate chains to a trusted root, and whether content was added to the document after it. Upload a signed pdf document, or leave the field empty to validate a document signed by this sample. The sample certificate is self-signed, so it is trusted only when it is passed as a root.

Signed PDF (optional):


Trust the sample certificate as a root

Sample code · C#
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using SelectPdf.Universal;

namespace SelectPdf.Samples.Pages
{
    public class DigitalSignaturesModel : PageModel
    {
        public void OnGet()
        {

        }

        // a signed pdf document to validate (optional)
        [BindProperty]
        public IFormFile FileSigned { get; set; }

        // trust the sample certificate as a root when validating
        [BindProperty]
        public bool ChkTrustSampleCertificate { get; set; } = true;

        // the validation results shown on the page
        public PdfSignatureValidationResult[] ValidationResults { get; private set; }

        public string ValidatedDocument { get; private set; }

        public IActionResult OnPost()
        {
            // create a signed pdf document
            byte[] pdf = CreateSignedDocument();

            // return resulted pdf document
            FileResult fileResult = new FileContentResult(pdf, "application/pdf");
            fileResult.FileDownloadName = "Document.pdf";
            return fileResult;
        }

        public IActionResult OnPostValidate()
        {
            // the document to validate: the uploaded one, or a document signed by this sample
            byte[] pdf;
            if (FileSigned != null && FileSigned.Length > 0)
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    FileSigned.CopyTo(ms);
                    pdf = ms.ToArray();
                }
                ValidatedDocument = Path.GetFileName(FileSigned.FileName);
            }
            else
            {
                pdf = CreateSignedDocument();
                ValidatedDocument = "a document signed by this sample";
            }

            // load the signed document in a security manager
            PdfSecurityManager manager = new PdfSecurityManager();
            manager.Load(pdf);

            if (ChkTrustSampleCertificate)
            {
                // trust the sample certificate as a root, in addition to the system's trusted roots
                // (the same call trusts your organization's own certificate authority)
                PdfDigitalCertificatesCollection roots =
                    PdfDigitalCertificatesStore.GetCertificates(CertificateFile(), "selectpdf");
                ValidationResults = manager.ValidateSignatures(roots);
            }
            else
            {
                // trust only the system's trusted roots
                ValidationResults = manager.ValidateSignatures();
            }

            manager.Close();

            // show the results on the page
            return Page();
        }

        private static string CertificateFile()
        {
            return Path.Combine(Startup.ServerPath, "wwwroot", "files", "selectpdf.pfx");
        }

        private static byte[] CreateSignedDocument()
        {
            // create a new pdf document
            PdfDocument doc = new PdfDocument();

            // add a new page to the document
            PdfPage page = doc.AddPage();

            // get image path
            // the image will be used to display the digital signature over it
            string imgFile = Path.Combine(Startup.ServerPath, "wwwroot", "images", "logo.png");

            // get certificate path
            string certFile = CertificateFile();

            // define a rendering result object
            PdfRenderingResult result;

            // create image element from file path
            PdfImageElement img = new PdfImageElement(0, 0, imgFile);
            result = page.Add(img);

            // get the #PKCS12 certificate from file
            PdfDigitalCertificatesCollection certificates =
                PdfDigitalCertificatesStore.GetCertificates(certFile, "selectpdf");
            PdfDigitalCertificate certificate = certificates[0];

            // create the digital signature object
            PdfDigitalSignatureElement signature =
                new PdfDigitalSignatureElement(result.PdfPageLastRectangle, certificate);
            signature.Reason = "SelectPdf";
            signature.ContactInfo = "SelectPdf";
            signature.Location = "SelectPdf";
            page.Add(signature);

            // save pdf document
            byte[] pdf = doc.Save();

            // close pdf document
            doc.Close();

            return pdf;
        }
    }
}