Digitally Sign an XML File in C#

void DigitallySignXMLDocument(string unsignedDocument, string signedDocument)
    XmlSignatureSha256 cs = new XmlSignatureSha256("");

    //Load the signature certificate from a PFX or P12 file
    X509Certificate2 cert = new X509Certificate2("cert.pfx", "123456", X509KeyStorageFlags.Exportable);

    //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. 
    //DigitalCertificate.SmartCardPin = "123456";

    cs.DigitalSignatureCertificate = cert;

    cs.IncludeKeyInfo = true;
    cs.IncludeSignatureCertificate = true;
    cs.RemoveWhitespaces = true;

    cs.SignatureType = XmlSignatureType.DefaultWithComments;

    //apply the digital signature
    cs.ApplyDigitalSignature(unsignedDocument, signedDocument);

void VerifyXMLSignature(string signedDocument)
    XmlSignature cv = new XmlSignature("");

    Console.WriteLine("Number of signatures: " + cv.GetNumberOfSignatures(signedDocument));

    //verify the signature
    Console.WriteLine("Signature validity status: " + cv.VerifyDigitalSignature(signedDocument));

    //signature algorithm
    Console.WriteLine("Signature algorithm: " + cv.GetSignatureAlgorithm(signedDocument));

See also: