コード例 #1
0
        static void Main(string[] args)
        {
            // Custom Values
            string filePath       = "c:/temp/demo.pdf";                                          // File to sign
            string fileMimeType   = "application/pdf";                                           // File MIME type
            string username       = "******";                                         // CoSign account username
            string password       = "******";                                         // CoSign account password
            string domain         = "";                                                          // CoSign account domain
            int    sigPageNum     = 1;                                                           // Create signature on the first page
            int    sigX           = 145;                                                         // Signature field X location
            int    sigY           = 125;                                                         // Signature field Y location
            int    sigWidth       = 160;                                                         // Signature field width
            int    sigHeight      = 45;                                                          // Signature field height
            string timeFormat     = "hh:mm:ss";                                                  // The display format of the time
            string dateFormat     = "dd/MM/yyyy";                                                // The display format of the date
            uint   appearanceMask = 11;                                                          // Elements to display on the signature field (11 = Graphical image + Signer name + Time)
            string signatureType  = "http://arx.com/SAPIWS/DSS/1.0/signature-field-create-sign"; // The actual operation of the Sign Request function
            string wsdlUrl        = "https://prime.cosigntrial.com:8080/sapiws/dss.asmx?WSDL";   // URL to the WSDL file

            try
            {
                // Read file contents
                byte[] fileBuffer = File.ReadAllBytes(filePath);

                // Set file contents + MIME type (the SOAP library automatically base64 encodes the data)
                DocumentType document = new DocumentType()
                {
                    Item = new DocumentTypeBase64Data()
                    {
                        Value    = fileBuffer,
                        MimeType = fileMimeType
                    }
                };

                ClaimedIdentity claimedIdentity = new ClaimedIdentity()
                {
                    Name = new NameIdentifierType()
                    {
                        Value         = username,
                        NameQualifier = domain
                    },
                    SupportingInfo = new CoSignAuthDataType()
                    {
                        LogonPassword = password
                    }
                };

                // Define signature field settings
                SAPISigFieldSettingsType sigFieldSettings = new SAPISigFieldSettingsType()
                {
                    Invisible          = false,
                    InvisibleSpecified = true,
                    X                       = sigX,
                    XSpecified              = true,
                    Y                       = sigY,
                    YSpecified              = true,
                    Width                   = sigWidth,
                    WidthSpecified          = true,
                    Height                  = sigHeight,
                    HeightSpecified         = true,
                    Page                    = sigPageNum,
                    PageSpecified           = true,
                    AppearanceMask          = appearanceMask,
                    AppearanceMaskSpecified = true,
                    TimeFormat              = new TimeDateFormatType()
                    {
                        TimeFormat             = timeFormat,
                        DateFormat             = dateFormat,
                        ExtTimeFormat          = ExtendedTimeFormatEnum.GMT,
                        ExtTimeFormatSpecified = true
                    }
                };

                // Build complete request object
                SignRequest signRequest = new SignRequest()
                {
                    InputDocuments = new RequestBaseTypeInputDocuments()
                    {
                        Items = new DocumentType[] { document }
                    },
                    OptionalInputs = new RequestBaseTypeOptionalInputs()
                    {
                        SignatureType              = signatureType,
                        ClaimedIdentity            = claimedIdentity,
                        SAPISigFieldSettings       = sigFieldSettings,
                        ReturnPDFTailOnly          = true,
                        ReturnPDFTailOnlySpecified = true
                    }
                };

                // Initiate service client
                DSS client = new DSS()
                {
                    Url = wsdlUrl
                };

                // Send the request
                DssSignResult response = client.DssSign(signRequest);

                // Check response output
                if ("urn:oasis:names:tc:dss:1.0:resultmajor:Success".Equals(response.Result.ResultMajor))
                {
                    // On success- append signature object to the source PDF document (the SOAP library automatically decodes the base64 encoded output)
                    byte[] signatureObjectBuffer = ((DssSignResultSignatureObjectBase64Signature)response.SignatureObject.Item).Value;
                    using (var fileStream = new FileStream(filePath, FileMode.Append))
                    {
                        fileStream.Write(signatureObjectBuffer, 0, signatureObjectBuffer.Length);
                    }
                }
                else
                {
                    // On failure- raise exception with the result error message
                    throw new Exception(response.Result.ResultMessage.Value);
                }

                Console.WriteLine("The document has been successfully signed!");
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.Message);
            }
        }
        //'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''


        //Sign PDF file
        public bool SignPDFFile(
            string FileToSign,
            string UserName,
            string Password,
            int X,
            int Y,
            int Width,
            int Height,
            int Page,
            bool isVisible)
        {
            //Create Request object contains signature parameters
            RequestBaseType Req = new RequestBaseType();

            Req.OptionalInputs = new RequestBaseTypeOptionalInputs();

            //Here Operation Type is set: Verify/Create Signature Field/Sign/etc
            Req.OptionalInputs.SignatureType = SignatureTypeFieldCreateSign;

            //Configure Create and Sign operation parameters:
            Req.OptionalInputs.ClaimedIdentity                              = new ClaimedIdentity();
            Req.OptionalInputs.ClaimedIdentity.Name                         = new NameIdentifierType();
            Req.OptionalInputs.ClaimedIdentity.Name.Value                   = UserName;    //User Name
            Req.OptionalInputs.ClaimedIdentity.Name.NameQualifier           = " ";         //Domain (relevant for Active Directory environment only)
            Req.OptionalInputs.ClaimedIdentity.SupportingInfo               = new CoSignAuthDataType();
            Req.OptionalInputs.ClaimedIdentity.SupportingInfo.LogonPassword = Password;    //User Password
            Req.OptionalInputs.SAPISigFieldSettings                         = new SAPISigFieldSettingsType();
            Req.OptionalInputs.SAPISigFieldSettings.X                       = X;           //Signature Field X coordinate
            Req.OptionalInputs.SAPISigFieldSettings.XSpecified              = true;
            Req.OptionalInputs.SAPISigFieldSettings.Y                       = Y;           //Signature Field Y coordinate
            Req.OptionalInputs.SAPISigFieldSettings.YSpecified              = true;
            Req.OptionalInputs.SAPISigFieldSettings.Page                    = Page;        //Page number the signature field will appear on
            Req.OptionalInputs.SAPISigFieldSettings.PageSpecified           = true;
            Req.OptionalInputs.SAPISigFieldSettings.Width                   = Width;       //Signature Field width
            Req.OptionalInputs.SAPISigFieldSettings.WidthSpecified          = true;
            Req.OptionalInputs.SAPISigFieldSettings.Height                  = Height;      //Signature Field Height
            Req.OptionalInputs.SAPISigFieldSettings.HeightSpecified         = true;
            Req.OptionalInputs.SAPISigFieldSettings.Invisible               = !isVisible;  //Specifies whether the signature will be visible or not
            Req.OptionalInputs.SAPISigFieldSettings.InvisibleSpecified      = true;


            // Set configuration parameters /////////////////////////////////////////////////////////
            int numConfigurationParams = 6;

            Req.OptionalInputs.ConfigurationValues = new ConfValueType[numConfigurationParams];
            for (int i = 0; i < numConfigurationParams; i++)
            {
                Req.OptionalInputs.ConfigurationValues[i] = new ConfValueType();
            }

            // Add reason
            Req.OptionalInputs.ConfigurationValues[0].ConfValueID = ConfIDEnum.Reason;
            Req.OptionalInputs.ConfigurationValues[0].Item        = "I am the author of this document";

            // Add TSA:

            /*
             * Req.OptionalInputs.ConfigurationValues[1].ConfValueID = ConfIDEnum.UseTimestamp;
             * Req.OptionalInputs.ConfigurationValues[1].Item = 1;
             *
             * Req.OptionalInputs.ConfigurationValues[2].ConfValueID = ConfIDEnum.TimestampURL;
             * Req.OptionalInputs.ConfigurationValues[2].Item = "http://www.ca-soft.com/request.aspx";
             *
             * Req.OptionalInputs.ConfigurationValues[3].ConfValueID = ConfIDEnum.TimestampAdditionalBytes;
             * Req.OptionalInputs.ConfigurationValues[3].Item = 4000;
             *
             * Req.OptionalInputs.ConfigurationValues[4].ConfValueID = ConfIDEnum.TimestampUser;
             * Req.OptionalInputs.ConfigurationValues[4].Item = "";
             *
             * Req.OptionalInputs.ConfigurationValues[5].ConfValueID = ConfIDEnum.TimestampPWD;
             * Req.OptionalInputs.ConfigurationValues[5].Item = "";
             *
             * // OCSP (NOTE: Server must contain comodo CA in order to use the following OCSP URL)
             * Req.OptionalInputs.ConfigurationValues[4].ConfValueID = ConfIDEnum.UseOCSP;
             * Req.OptionalInputs.ConfigurationValues[4].Item = 1;
             *
             * Req.OptionalInputs.ConfigurationValues[5].ConfValueID = ConfIDEnum.OCSPURL;
             * Req.OptionalInputs.ConfigurationValues[5].Item = "ocsp.comodoca.com";
             */
            // End setting configuration parameters ////////////////////////////////////////////////

            //Set Session ID
            Req.RequestID = Guid.NewGuid().ToString();

            //Prepare the Data to be signed
            DocumentType           doc1    = new DocumentType();
            DocumentTypeBase64Data b64data = new DocumentTypeBase64Data();

            Req.InputDocuments       = new RequestBaseTypeInputDocuments();
            Req.InputDocuments.Items = new object[1];

            b64data.MimeType = "application/pdf";     //Can also be: application/msword, image/tiff, pplication/octet-string (ocsp/tsa are supported in PDF only)
            Req.OptionalInputs.ReturnPDFTailOnlySpecified = true;
            Req.OptionalInputs.ReturnPDFTailOnly          = true;
            b64data.Value = ReadFile(FileToSign, true); //Read the file to the Bytes Array

            doc1.Item = b64data;
            Req.InputDocuments.Items[0] = doc1;

            //Call sign service
            ResponseBaseType Resp = null;

            try
            {
                // Create the Web Service client object
                DSS service = new DSS();
                service.Url = "https://prime.cosigntrial.com:8080/SAPIWS/dss.asmx";  //This url is constant and shouldn't be changed

                SignRequest sreq = new SignRequest();
                sreq.InputDocuments = Req.InputDocuments;
                sreq.OptionalInputs = Req.OptionalInputs;

                //Perform Signature operation
                Resp = service.DssSign(sreq);

                if (Resp.Result.ResultMajor != Success)
                {
                    MessageBox.Show("Error: " + Resp.Result.ResultMajor + " " +
                                    Resp.Result.ResultMinor + " " +
                                    Resp.Result.ResultMessage.Value, "Error");
                    return(false);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
                if (ex is WebException)
                {
                    WebException we          = ex as WebException;
                    WebResponse  webResponse = we.Response;
                    if (webResponse != null)
                    {
                        MessageBox.Show(we.Response.ToString(), "Web Response");
                    }
                }
                return(false);
            }


            //Handle Reply
            DssSignResult sResp = (DssSignResult)Resp;



            //object sig = sResp.SignatureObject.Item;
            //SignatureObjectTypeBase64Signature sig = (SignatureObjectTypeBase64Signature) sResp.SignatureObject.Item;
            DssSignResultSignatureObjectBase64Signature sig = (DssSignResultSignatureObjectBase64Signature)sResp.SignatureObject.Item;

            byte[] signature = sig.Value;

            return(PDFAttachSignature(FileToSign, signature, true)); //Attach Signature to the PDF file
        }
        //'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''


        //Sign PDF file
        public bool SignPDFFile(
            string CoSignDNS,
            string FileToSign,
            string UserName,
            string Password,
            string PdfPassword,
            string grSigName,
            int X,
            int Y,
            int Width,
            int Height,
            int Page,
            bool isVisible,
            int GMTOffset,
            int AppearanceMask)
        {
            //Create Request object contains signature parameters
            RequestBaseType Req = new RequestBaseType();

            Req.OptionalInputs = new RequestBaseTypeOptionalInputs();

            //Here Operation Type is set: Verify/Create Signature Field/Sign/etc
            Req.OptionalInputs.SignatureType = SignatureTypeFieldCreateSign;

            //Configure Create and Sign operation parameters:
            Req.OptionalInputs.ClaimedIdentity                              = new ClaimedIdentity();
            Req.OptionalInputs.ClaimedIdentity.Name                         = new NameIdentifierType();
            Req.OptionalInputs.ClaimedIdentity.Name.Value                   = UserName;    //User Name
            Req.OptionalInputs.ClaimedIdentity.Name.NameQualifier           = " ";         //Domain (relevant for Active Directory environment only)
            Req.OptionalInputs.ClaimedIdentity.SupportingInfo               = new CoSignAuthDataType();
            Req.OptionalInputs.ClaimedIdentity.SupportingInfo.LogonPassword = Password;    //User Password
            Req.OptionalInputs.SAPISigFieldSettings                         = new SAPISigFieldSettingsType();
            Req.OptionalInputs.SAPISigFieldSettings.X                       = X;           //Signature Field X coordinate
            Req.OptionalInputs.SAPISigFieldSettings.XSpecified              = true;
            Req.OptionalInputs.SAPISigFieldSettings.Y                       = Y;           //Signature Field Y coordinate
            Req.OptionalInputs.SAPISigFieldSettings.YSpecified              = true;
            Req.OptionalInputs.SAPISigFieldSettings.Page                    = Page;        //Page number the signature field will appear on
            Req.OptionalInputs.SAPISigFieldSettings.PageSpecified           = true;
            Req.OptionalInputs.SAPISigFieldSettings.Width                   = Width;       //Signature Field width
            Req.OptionalInputs.SAPISigFieldSettings.WidthSpecified          = true;
            Req.OptionalInputs.SAPISigFieldSettings.Height                  = Height;      //Signature Field Height
            Req.OptionalInputs.SAPISigFieldSettings.HeightSpecified         = true;
            Req.OptionalInputs.SAPISigFieldSettings.Invisible               = !isVisible;  //Specifies whether the signature will be visible or not
            Req.OptionalInputs.SAPISigFieldSettings.InvisibleSpecified      = true;

            //display only graphical signature in signature field
            Req.OptionalInputs.SAPISigFieldSettings.AppearanceMask          = (uint)AppearanceMask;
            Req.OptionalInputs.SAPISigFieldSettings.AppearanceMaskSpecified = true;

            int numConfigurationParams = 0;

            if (!string.IsNullOrEmpty(PdfPassword))
            {
                numConfigurationParams += 2;
            }
            if (!string.IsNullOrEmpty(grSigName))
            {
                numConfigurationParams += 1;
            }
            if ((GMTOffset != 0) && ((GMTOffset % 60) == 0))
            {
                numConfigurationParams += 1;
            }

            if (numConfigurationParams > 0)
            {
                Req.OptionalInputs.ConfigurationValues = new ConfValueType[numConfigurationParams];
                for (int i = 0; i < numConfigurationParams; i++)
                {
                    Req.OptionalInputs.ConfigurationValues[i] = new ConfValueType();
                }
            }

            int confArrayCurrentLoc = -1;

            if (!string.IsNullOrEmpty(PdfPassword))
            {
                // Add DECRYPT PDF password
                confArrayCurrentLoc += 1;
                Req.OptionalInputs.ConfigurationValues[confArrayCurrentLoc].ConfValueID = ConfIDEnum.PDFOwnerPwd;
                Req.OptionalInputs.ConfigurationValues[confArrayCurrentLoc].Item        = PdfPassword;

                confArrayCurrentLoc += 1;
                Req.OptionalInputs.ConfigurationValues[confArrayCurrentLoc].ConfValueID = ConfIDEnum.PDFUserPwd;
                Req.OptionalInputs.ConfigurationValues[confArrayCurrentLoc].Item        = PdfPassword;
            }

            //choose the 'grSigName' graphical signature from signer account
            if (!string.IsNullOrEmpty(grSigName))
            {
                //specify graphical signature name
                confArrayCurrentLoc += 1;
                Req.OptionalInputs.ConfigurationValues[confArrayCurrentLoc].ConfValueID = ConfIDEnum.GRSigPrefName;
                Req.OptionalInputs.ConfigurationValues[confArrayCurrentLoc].Item        = grSigName;
            }

            if ((GMTOffset != 0) && ((GMTOffset % 60) == 0))
            {
                //GMTOffset
                confArrayCurrentLoc += 1;
                Req.OptionalInputs.ConfigurationValues[confArrayCurrentLoc].ConfValueID = ConfIDEnum.GMTOffset;
                Req.OptionalInputs.ConfigurationValues[confArrayCurrentLoc].Item        = GMTOffset;
            }

            // Add reason
            //Req.OptionalInputs.ConfigurationValues[0].ConfValueID = ConfIDEnum.Reason;
            //Req.OptionalInputs.ConfigurationValues[0].Item = "I am the author of this document";

            // Add TSA:

            /*
             * Req.OptionalInputs.ConfigurationValues[1].ConfValueID = ConfIDEnum.UseTimestamp;
             * Req.OptionalInputs.ConfigurationValues[1].Item = 1;
             *
             * Req.OptionalInputs.ConfigurationValues[2].ConfValueID = ConfIDEnum.TimestampURL;
             * Req.OptionalInputs.ConfigurationValues[2].Item = "http://www.ca-soft.com/request.aspx";
             *
             * Req.OptionalInputs.ConfigurationValues[3].ConfValueID = ConfIDEnum.TimestampAdditionalBytes;
             * Req.OptionalInputs.ConfigurationValues[3].Item = 4000;
             *
             * Req.OptionalInputs.ConfigurationValues[4].ConfValueID = ConfIDEnum.TimestampUser;
             * Req.OptionalInputs.ConfigurationValues[4].Item = "";
             *
             * Req.OptionalInputs.ConfigurationValues[5].ConfValueID = ConfIDEnum.TimestampPWD;
             * Req.OptionalInputs.ConfigurationValues[5].Item = "";
             *
             * // OCSP (NOTE: Server must contain comodo CA in order to use the following OCSP URL)
             * Req.OptionalInputs.ConfigurationValues[4].ConfValueID = ConfIDEnum.UseOCSP;
             * Req.OptionalInputs.ConfigurationValues[4].Item = 1;
             *
             * Req.OptionalInputs.ConfigurationValues[5].ConfValueID = ConfIDEnum.OCSPURL;
             * Req.OptionalInputs.ConfigurationValues[5].Item = "ocsp.comodoca.com";
             */
            // End setting configuration parameters ////////////////////////////////////////////////

            //Set Session ID
            Req.RequestID = Guid.NewGuid().ToString();

            //Prepare the Data to be signed
            DocumentType           doc1    = new DocumentType();
            DocumentTypeBase64Data b64data = new DocumentTypeBase64Data();

            Req.InputDocuments       = new RequestBaseTypeInputDocuments();
            Req.InputDocuments.Items = new object[1];

            b64data.MimeType = "application/pdf";     //Can also be: application/msword, image/tiff, pplication/octet-string (ocsp/tsa are supported in PDF only)
            //Req.OptionalInputs.ReturnPDFTailOnlySpecified = true;
            Req.OptionalInputs.ReturnPDFTailOnlySpecified = false;
            Req.OptionalInputs.ReturnPDFTailOnly          = false;
            b64data.Value = ReadFile(FileToSign, true); //Read the file to the Bytes Array

            doc1.Item = b64data;
            Req.InputDocuments.Items[0] = doc1;

            //Call sign service
            ResponseBaseType Resp = null;

            try
            {
                // Create the Web Service client object
                DSS service = new DSS();
                service.Url = "https://" + CoSignDNS + ":8080/sapiws/dss.asmx";

                SignRequest sreq = new SignRequest();
                sreq.InputDocuments = Req.InputDocuments;
                sreq.OptionalInputs = Req.OptionalInputs;

                //Perform Signature operation
                Resp = service.DssSign(sreq);

                if (Resp.Result.ResultMajor != Success)
                {
                    MessageBox.Show("Error: " + Resp.Result.ResultMajor + " " +
                                    Resp.Result.ResultMinor + " " +
                                    Resp.Result.ResultMessage.Value, "Error");
                    return(false);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
                if (ex is WebException)
                {
                    WebException we          = ex as WebException;
                    WebResponse  webResponse = we.Response;
                    if (webResponse != null)
                    {
                        MessageBox.Show(we.Response.ToString(), "Web Response");
                    }
                }
                return(false);
            }

            //Handle Reply
            DssSignResult sResp = (DssSignResult)Resp;

            //return Tail only code
            //DssSignResultSignatureObjectBase64Signature sig = (DssSignResultSignatureObjectBase64Signature)sResp.SignatureObject.Item;
            //byte[] signature = sig.Value;
            //return PDFAttachSignature(FileToSign, signature, true); //Attach Signature to the PDF file

            DocumentTypeBase64Data signedDoc = (DocumentTypeBase64Data)sResp.OptionalOutputs.DocumentWithSignature.Document.Item;

            byte[] docData = signedDoc.Value;
            //return PDFAttachSignature(FileToSign + ".signed.pdf", docData, true);
            return(PDFReWrite(FileToSign, docData, true));
        }