digital-signaturexpsdocument

XpsDocument.SignDigitally throws NullReferenceException on IsSignable


I ran into a problem with the method mentioned in the title. If I try to sign an XPS document, it runs into NullReferenceException:

at System.Windows.Xps.Packaging.XpsDocument.get_IsSignable() at System.Windows.Xps.Packaging.XpsDocument.SignDigitally(X509Certificate certificate, Boolean embedCertificate, XpsDigSigPartAlteringRestrictions restrictions, String signatureId, Boolean testIsSignable) at System.Windows.Xps.Packaging.XpsDocument.SignDigitally(X509Certificate certificate, Boolean embedCertificate, XpsDigSigPartAlteringRestrictions restrictions)

Any advise will appreciated.

    if (sign_digitally)
    {
        UserCertificateSelector selector = new UserCertificateSelector();
        if (selector.ShowDialog() == true)
            {
                var certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
certStore.Open(OpenFlags.ReadOnly);
#if DEBUG
                X509CertificateCollection collection = certStore.Certificates;
#else
                X509CertificateCollection collection = certStore.Certificates.Find(X509FindType.FindByThumbprint, selector.SelectedCertificate.CertificateThumbPrint,true);
#endif
                if (collection.Count > 0)
                {
                    xpsDoc.SignDigitally(collection[0], true, XpsDigSigPartAlteringRestrictions.None);
                 }
             }
         }
...

Solution

  • Make sure you deal with XPS file format, not OXPS. Both can be open as XpsDocument but only XPS can be signed. You can check "XpsDocument.IsSignable" flag once you open the file - for OXPS it will be null.