1

I am having a pdf with multiple signature fields. I am using iTextSharp in order to create the pdf with the signature fields and I am trying to sign each signature field with the CoSign SAPI. When I append the signature object from the response of the call, the signature is invalid.

Below is an example of the code I use in order to sign an existing signature field from a pdf document with many (signature fields):

public void SignDocument(string filePath, string fieldName, string username, string password)
        {
            byte[] fileBuffer = File.ReadAllBytes(filePath);
            DocumentType document = new DocumentType()
            {
                Item = new DocumentTypeBase64Data()
                {
                    Value = fileBuffer,
                    MimeType = "application/pdf"
                }
            };
            ClaimedIdentity claimedIdentity = new ClaimedIdentity()
            {
                Name = new NameIdentifierType()
                {
                    Value = username
                },
                SupportingInfo = new CoSignAuthDataType()
                {
                    LogonPassword = password
                }
            };
            SAPISigFieldSettingsType sigFieldSettings = new SAPISigFieldSettingsType()
            {
                Invisible = true,
                InvisibleSpecified = true,
                X = 145,
                XSpecified = true,
                Y = 125,
                YSpecified = true,
                Width = 160,
                WidthSpecified = true,
                Height = 45,
                HeightSpecified = true,
                Page = 1,
                PageSpecified = true,
                AppearanceMask = 11,
                AppearanceMaskSpecified = true,
                TimeFormat = new TimeDateFormatType()
                {
                    TimeFormat = "hh:mm:ss",
                    DateFormat = "dd/MM/yyyy",
                    ExtTimeFormat = ExtendedTimeFormatEnum.GMT,
                    ExtTimeFormatSpecified = true
                }
            };

            SignRequest signRequest = new SignRequest()
            {
                InputDocuments = new RequestBaseTypeInputDocuments()
                {
                    Items = new DocumentType[] { document }
                },
                OptionalInputs = new RequestBaseTypeOptionalInputs()
                {
                    SignatureType = "http://arx.com/SAPIWS/DSS/1.0/signature-field-sign",
                    ClaimedIdentity = claimedIdentity,
                    SAPISigFieldSettings = sigFieldSettings,
                    ReturnPDFTailOnly = true,
                    ReturnPDFTailOnlySpecified = true,
                    SignatureFieldName = fieldName
                }
            };
            DssSignResult response = _client.DssSign(signRequest);

            if (response.Result.ResultMajor.Equals(SIGN_SUCCESS_RESULT_MAJOR))
            {
                byte[] signatureBuffer = ((DssSignResultSignatureObjectBase64Signature)response.SignatureObject.Item).Value;
                using (var fileStream = new FileStream(filePath, FileMode.Append))
                {
                    fileStream.Write(signatureBuffer, 0, signatureBuffer.Length);
                }
            }
            else
            {
                throw new Exception(response.Result.ResultMessage.Value);
            }
        }

file

This is the file that I want to sign. I am trying to sign the signature field "sig2-9" but the signature is invalid with message "There have been changes made to this document that invalidate the signature". Sorry for not posting the signed document but the certificate owner doesn't want to share his personal information.

signed file

This is the signed file with the invalid signature.

signed file 2

This is a file that I signed with another CoSign api call. This call creates the signature field and signs it, with the same certificate as the "signed file". As you can see the signature in this example is valid. In this example I used the "http://arx.com/SAPIWS/DSS/1.0/signature-field-create-sign" signature type.

iCantSeeSharp
  • 3,880
  • 4
  • 42
  • 65
Kostas
  • 1,803
  • 1
  • 8
  • 8
  • I don't recognize the code (probably because it's cosign code), but if you create the PDF with iText, why don't you sign the PDF with iText? – Bruno Lowagie Jul 11 '17 at 07:38
  • @BrunoLowagie *"why don't you sign the PDF with iText"* - I think the question is about signing via DocuSign. Is there an easy way to integrate DocuSign into iText signing? (I actually have not yet played around with DocuSign, so I have no idea how complicated or easy that would be...) – mkl Jul 11 '17 at 09:11
  • DocuSign is a customer of iText, so both technologies should work well together, but I am not familiar with the CoSign API. – Bruno Lowagie Jul 11 '17 at 09:22
  • @BrunoLowagie - I can't user the iTextSharp in order to sign the pdf file, because the private key is being stored at a CoSign server. I make the Soap call at the CoSign server with the pdf file and the server returns the signed hash of the file. When I am finishing the signing and opening the file the signature is not valid. – Kostas Jul 12 '17 at 06:47
  • @KostasPatakakis Can you share an example PDF signed by your code for analysis? – mkl Jul 12 '17 at 15:44
  • @BrunoLowagie "*DocuSign is a customer of iText, so both technologies should work well together*" - At least in one direction... Most likely they integrated iText on their server side, but I wouldn't automatically assume they developed their client side APIs for easy use from inside an iText signing workflow... ;) – mkl Jul 12 '17 at 15:50
  • 1
    Well @mkl, assuming that Kostas is a customer of CoSign/Docusign, the best way to solve this is to contact customer support at Docusign, and ask them to file a support ticket at iText. – Bruno Lowagie Jul 13 '17 at 07:00
  • Yes, in particular as there don't currently seem to be many CoSign API experts active here... ;) – mkl Jul 13 '17 at 13:17
  • Kostas, please also share a copy of the PDF after signing, so we can analyse what is broken. As developer you surely have developer DSA access; if the certificate owner does not want his certificate shown, your developer certificate should be ok to show. – mkl Jul 17 '17 at 13:51
  • I ran your signed file through a number of validators. Some say it's ok, some say the hash is wrong, some even stop while parsing due to some perceived format error. I'll look into that some more later. I assume that there is some minor detail in the signature (probably some seldom inspected attribute of an embedded certificate) which is wrong but simply overlooked by many validators. – mkl Jul 19 '17 at 08:24
  • One issue is that one certificate uses the ASN.1 type `PrintableString` for the **emailAddress** RDN. This is a bad choice as the '@' is not in the character set allowed for that type. The value in that `PrintableString` is "cmp@dataverse.gr" which unsurprisingly does contain a '@'. Furthermore, the emailAddress attribute is specified to have an `IA5String` value. Strict parsers may, therefore, reject that certificate. I'm not sure, though, whether this is the reason why Adobe and SD DSS have issues with the file. – mkl Jul 19 '17 at 11:11
  • @mkl Well, I don't believe that there is a problem with the certificate because as you can see the "signed file 2" has a signature with the same certificate and it is valid. – Kostas Jul 20 '17 at 07:50
  • *I don't believe that there is a problem with the certificate* - I *know* there is a problem with the certificate: As explained above it strictly speaking has errors. It merely does not seem to be the cause of the observed behavior. – mkl Jul 20 '17 at 08:00
  • Considering the latest edit, the main difference seems to be that the non-working code tries to fill an existing signature field while the working creates a new, invisible one. Thus, either the SAPI has generally a problem with signing existing fields (which I don't believe) or there is something special about the fields in question. As I've already mentioned in a comment to Aviv's answer, the existing signature fields make use of signature lock dictionaries. You might try instead using simpler signature fields without lock dictionaries, maybe SAPI does not support them. – mkl Jul 20 '17 at 10:31

1 Answers1

1

Bruno and mkl.

My name is Aviv Simionovici and I am a DSA (DocuSign Signature Appliance) API specialist from DocuSign.

Your code seems fine, although you might forgot the following:

Req.OptionalInputs.ReturnPDFTailOnlySpecified = true;
Req.OptionalInputs.ReturnPDFTailOnly = true;

For your convenience, here is a function that appends the signature to the PDF:

public bool PDFAttachSignature(string PDFFile, byte[] Signature, bool isDisplayErrorsGUI)
{
   if (Signature == null) return false;
   try
   {
      FileStream f = File.OpenWrite(PDFFile);
      f.Position = f.Length;  //seek to the end of file
      f.Write(Signature, 0, Signature.Length); //write the signature content
      f.Close();
   }
   catch (Exception ex)
   {
      if (isDisplayErrorsGUI)
         MessageBox.Show("Error Attaching the signature\n\nException:\n" + ex.Message, "Error");
         return false;
   }

   return true;
}

The whole visual studio project with the sample is here.

You stated that the signature is not valid when you open the PDF with a PDF viewer. That can also happen due to untrusted certificate in your certificate chain ending in your DSA root certificate. Or because revocation on the certificates on that chain cannot be performed. Please see why the signature is not valid.

  • While it is nice to be addressed personally, the main addressee should be Kostas Patakakis, the Original Poster of the question. Furthermore, *"Please see why the signature is not valid."* - to find out about this, I already asked the OP in a comment to share a sample PDF illustrating the issue. – mkl Jul 17 '17 at 08:57
  • Thanks for the reply Aviv but I have the same problem with your solution. I updated the post and I attached the pdf that I want to sign. – Kostas Jul 17 '17 at 13:28
  • @Aviv Kostas' sample document contains signature lock dictionaries. Does DSA / Docusign handle them appropriately? – mkl Jul 17 '17 at 13:53
  • @Kostas - When I open the signed document I get an error saying "The revocation status of the certificate or one of the certificates in the certificate chain is unknown". This error is not related to the code producing the signature. Actually, recently the CRL's pointed from one of the intermediates certificates on the trust chain of prime.cosigntrial.com became invalid. You should expect it in every signature performed with old accounts from prime.cosigntrial.com. I suggest to try the following: 1) Sign with CoSign Client 2) remove the "tail only" 3) sign with cosigndemo.arx.com – Aviv Simionovici Jul 19 '17 at 06:23
  • @AvivSimionovici When I open the OP's [signed file](https://www.dropbox.com/s/j6eme53lleaok13/test_signed.pdf?dl=0) in Adobe Acrobat Reader DC, it shows [these signature properties](https://i.stack.imgur.com/ncA1Z.png); the problem is not any revocation or trust issue, it is that Adobe claims "the document has been altered or corrupted since the signature was applied." As Adobe shows this even after cutting back the PDF to the actually signed revision, this is not due to any additions in incremental updates either. Adobe really considers the hash value wrong. – mkl Jul 19 '17 at 11:21
  • @AvivSimionovici I don't believe that there is a problem with the account because the "signed file 2" has a valid signature with the same certificate from the same account. As for the "remove the "tail only" " I have done that in order to retrieve the whole signed document and has the same ivalid signature as the "signed file" – Kostas Jul 20 '17 at 07:57