Digitally Sign an Office Document (.DOCX, .XLSX, .PPTX) in C#

void DigitallySignOfficeDocument()
{
    OfficeSignature cs = new OfficeSignature("");

    //Load the signature certificate from a PFX or P12 file
    //cs.DigitalSignatureCertificate = DigitalCertificate.LoadCertificate("cert.pfx", "123456");

    //Load the certificate from Microsoft Store. 
    //The smart card or USB token certificates are usually available on Microsoft Certificate Store (start - run - certmgr.msc).
    //If the smart card certificate not appears on Microsoft Certificate Store it cannot be used by the library
    cs.DigitalSignatureCertificate = DigitalCertificate.LoadCertificate(false, string.Empty, "Select Certificate", "Select the certificate for digital signature");

    //The smart card PIN dialog can be bypassed for some smart cards/USB Tokens. 
    //ATTENTION: This feature will NOT work for all available smart card/USB Tokens becauase of the drivers or other security measures.
    DigitalCertificate.SmartCardPin = "123456";

    //apply the digital signature to a DOCX, XLSX or PPTX Office document
    cs.ApplyDigitalSignature("Document.docx", "SignedDocument.docx");

    Console.WriteLine("Number of signatures: " + cs.GetNumberOfSignatures("SignedDocument.docx"));

    //verify the first signature
    Console.WriteLine("Signature validity status: " + cs.VerifyDigitalSignature("SignedDocument.docx", 1));
}

See also: