/**
         * @Method Method that inserts the GraphSign in the pdf document and call for signing it
         * @Params DocumentData source document to be signed
         * @Params GraphSign sign Image and metadata about the Graphical Sign
         * @Params signer data
         * @Return true if the document is correctly signed, false if something wrong
         */
        public bool doSignature(DocumentData source,GraphSign sign, string metadata, Signer signer)
        {
            bool result = false;
            bool insertedSign = false;
             /*           if (this.open(source))
            {
                Dictionary<String, String> hMap = this.reader.Info;
                String keywords = "";
                hMap.TryGetValue("Keywords",out keywords);
                keywords += metadata+Properties.Settings.Default.stringSeparator;
                this.Log.Debug("Keywords length " + keywords.Length);
                hMap.Remove("Keywords");
                hMap.Add("Keywords", keywords);
                //Copy PDF
                this.Log.Debug("Starting PDF copy");
                for (int i = 1; i <= reader.NumberOfPages; i++)
                {
                    doc.SetPageSize(reader.GetPageSize(i));
                    doc.NewPage();
                    PdfContentByte cb = writer.DirectContent;
                    PdfImportedPage importedPage = writer.GetImportedPage(reader, i);

                    int rotation = reader.GetPageRotation(i);
                    if (rotation == 90 || rotation == 270)
                        cb.AddTemplate(importedPage, 0, -1.0F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(i).Height);
                    else
                        cb.AddTemplate(importedPage, 1.0F, 0, 0, 1.0F, 0, 0);
                    //Insert Graph image on coordenates
                    if (i == signer.Page)
                    {
                        this.Log.Debug(String.Format("Trying to insert graph sign in Page {0}, x={1}, y={2}", signer.Page, signer.X, signer.Y));
                        insertedSign = this.insertGraphSign(sign, cb, signer.X, signer.Y);
                    }

                }
              * */
            insertedSign = true;
                if (insertedSign)
                {
                //    this.Log.Debug("Graph Sign inserted correctly, starting PAdES process");
                    //Do PAdES
                //    this.close();
                    DigitalSignUtils.signPDF(source, metadata, sign,signer);
                    this.Log.Debug("Moving files");
                    if(File.Exists(source.Docpath+"-signed.pdf"))
                        File.Delete(source.Docpath+"-signed.pdf");
                    File.Copy(source.Docsignedpath, source.Docpath + "-signed.pdf");
                    result = true;
                }
             //       }
            //        this.close();
            return result;
        }
示例#2
0
 /**
  *
  */
 private String[] getSignString(GraphSign sign)
 {
     String[] result = new String[sign.Points.Count];
     int i = 0;
     foreach (BioSignPoint point in sign.Points)
     {
         result[i] = "" + point.Order + "," + point.X + "," + point.Y + "," + point.Pressure + "," + point.Time.Ticks;
         i++;
     }
     return result;
 }
 private void onGetReportException(wgssSTU.ITabletEventsException tabletEventsException)
 {
     try
     {
         tabletEventsException.getException();
     }
     catch (Exception e)
     {
         //TODO Log4NET
         m_tablet.disconnect();
         m_tablet = null;
         this.sign = null;
         this.Close();
     }
 }
        public WacomPadForm(wgssSTU.IUsbDevice usbDevice, int points)
        {
            semaphore = true;
            this.minPoints = points;
            if (presingString != null)
            {
                presignText.Text = presingString;
            }
            this.sign = new GraphSign();
            // This is a DPI aware application, so ensure you understand how .NET client coordinates work.
            // Testing using a Windows installation set to a high DPI is recommended to understand how
            // values get scaled or not.
            this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;

            InitializeComponent();

            m_tablet = new wgssSTU.Tablet();
            wgssSTU.ProtocolHelper protocolHelper = new wgssSTU.ProtocolHelper();

            // A more sophisticated applications should cycle for a few times as the connection may only be
            // temporarily unavailable for a second or so.
            // For example, if a background process such as Wacom STU Display
            // is running, this periodically updates a slideshow of images to the device.

            wgssSTU.IErrorCode ec = m_tablet.usbConnect(usbDevice, true);
            if (ec.value == 0)
            {
                m_capability = m_tablet.getCapability();
                m_information = m_tablet.getInformation();
            }
            else
            {
                throw new Exception(ec.message);
            }

            this.SuspendLayout();
            this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;

            // Set the size of the client window to be actual size,
            // based on the reported DPI of the monitor.

            Size clientSize = new Size((int)(m_capability.tabletMaxX / 2540F * 96F), (int)(m_capability.tabletMaxY / 2540F * 96F));
            this.ClientSize = clientSize;
            this.ResumeLayout();

            m_btns = new Button[3];
            if (usbDevice.idProduct != 0x00a2)
            {
                // Place the buttons across the bottom of the screen.

                int w2 = m_capability.screenWidth / 3;
                int w3 = m_capability.screenWidth / 3;
                int w1 = m_capability.screenWidth - w2 - w3;
                int y = m_capability.screenHeight * 6 / 7;
                int h = m_capability.screenHeight - y;

                presignText.Bounds = new Rectangle(0, 0, m_capability.screenWidth, h);
                m_btns[0].Bounds = new Rectangle(0, y, w1, h);
                m_btns[1].Bounds = new Rectangle(w1, y, w2, h);
                m_btns[2].Bounds = new Rectangle(w1 + w2, y, w3, h);
            }
            else
            {
                // The STU-300 is very shallow, so it is better to utilise
                // the buttons to the side of the display instead.

                int x = m_capability.screenWidth * 3 / 4;
                int w = m_capability.screenWidth - x;

                int h2 = m_capability.screenHeight / 3;
                int h3 = m_capability.screenHeight / 3;
                int h1 = m_capability.screenHeight - h2 - h3;

                m_btns[0].Bounds = new Rectangle(x, 0, w, h1);
                m_btns[1].Bounds = new Rectangle(x, h1, w, h2);
                m_btns[2].Bounds = new Rectangle(x, h1 + h2, w, h3);
            }
            m_btns[0].Text = "Aceptar";
            m_btns[1].Text = "Borrar";
            m_btns[2].Text = "Cancelar";
            m_btns[0].Click = new EventHandler(btnOk_Click);
            m_btns[1].Click = new EventHandler(btnClear_Click);
            m_btns[2].Click = new EventHandler(btnCancel_Click);

            // Disable color if the STU-520 bulk driver isn't installed.
            // This isn't necessary, but uploading colour images with out the driver
            // is very slow.

            // Calculate the encodingMode that will be used to update the image
            ushort idP = m_tablet.getProductId();
            wgssSTU.encodingFlag encodingFlag = (wgssSTU.encodingFlag)protocolHelper.simulateEncodingFlag(idP, 0);
            bool useColor = false;
            if ((encodingFlag & (wgssSTU.encodingFlag.EncodingFlag_16bit | wgssSTU.encodingFlag.EncodingFlag_24bit)) != 0)
            {
                if (m_tablet.supportsWrite())
                    useColor = true;
            }
            if ((encodingFlag & wgssSTU.encodingFlag.EncodingFlag_24bit) != 0)
            {
                m_encodingMode = m_tablet.supportsWrite() ? wgssSTU.encodingMode.EncodingMode_24bit_Bulk : wgssSTU.encodingMode.EncodingMode_24bit;
            }
            else if ((encodingFlag & wgssSTU.encodingFlag.EncodingFlag_16bit) != 0)
            {
                m_encodingMode = m_tablet.supportsWrite() ? wgssSTU.encodingMode.EncodingMode_16bit_Bulk : wgssSTU.encodingMode.EncodingMode_16bit;
            }
            else
            {
                // assumes 1bit is available
                m_encodingMode = wgssSTU.encodingMode.EncodingMode_1bit;
            }

            // Size the bitmap to the size of the LCD screen.
            // This application uses the same bitmap for both the screen and client (window).
            // However, at high DPI, this bitmap will be stretch and it would be better to
            // create individual bitmaps for screen and client at native resolutions.
            m_bitmap = new Bitmap(m_capability.screenWidth, m_capability.screenHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            {
                Graphics gfx = Graphics.FromImage(m_bitmap);
                gfx.Clear(Color.White);

                // Uses pixels for units as DPI won't be accurate for tablet LCD.
                Font font = new Font(FontFamily.GenericSansSerif, m_btns[0].Bounds.Height / 2F, GraphicsUnit.Pixel);
                StringFormat sf = new StringFormat();
                sf.Alignment = StringAlignment.Center;
                sf.LineAlignment = StringAlignment.Center;

                if (useColor)
                {
                    gfx.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
                }
                else
                {
                    // Anti-aliasing should be turned off for monochrome devices.
                    gfx.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;
                }

                gfx.DrawRectangle(Pens.Black, presignText.Bounds);
                gfx.DrawString(presignText.Text, font, Brushes.Black, presignText.Bounds, sf);

                // Draw the buttons
                for (int i = 0; i < m_btns.Length; ++i)
                {
                    if (useColor)
                    {
                        gfx.FillRectangle(Brushes.LightGray, m_btns[i].Bounds);
                    }
                    gfx.DrawRectangle(Pens.Black, m_btns[i].Bounds);
                    gfx.DrawString(m_btns[i].Text, font, Brushes.Black, m_btns[i].Bounds, sf);
                }

                gfx.Dispose();
                font.Dispose();

                // Finally, use this bitmap for the window background.
                this.BackgroundImage = m_bitmap;
                this.BackgroundImageLayout = ImageLayout.Stretch;
            }

            // Now the bitmap has been created, it needs to be converted to device-native
            // format.
            {

                // Unfortunately it is not possible for the native COM component to
                // understand .NET bitmaps. We have therefore convert the .NET bitmap
                // into a memory blob that will be understood by COM.

                System.IO.MemoryStream stream = new System.IO.MemoryStream();
                m_bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                m_bitmapData = (byte[])protocolHelper.resizeAndFlatten(stream.ToArray(), 0, 0, (uint)m_bitmap.Width, (uint)m_bitmap.Height, m_capability.screenWidth, m_capability.screenHeight, (byte)m_encodingMode, wgssSTU.Scale.Scale_Fit, 0, 0);
                protocolHelper = null;
                stream.Dispose();
            }

            // If you wish to further optimize image transfer, you can compress the image using
            // the Zlib algorithm.

            bool useZlibCompression = false;
            if (!useColor && useZlibCompression)
            {
                // m_bitmapData = compress_using_zlib(m_bitmapData); // insert compression here!
                m_encodingMode |= wgssSTU.encodingMode.EncodingMode_Zlib;
            }

            // Calculate the size and cache the inking pen.

            SizeF s = this.AutoScaleDimensions;
            float inkWidthMM = 0.7F;
            m_penInk = new Pen(Color.DarkBlue, inkWidthMM / 25.4F * ((s.Width + s.Height) / 2F));
            m_penInk.StartCap = m_penInk.EndCap = System.Drawing.Drawing2D.LineCap.Round;
            m_penInk.LineJoin = System.Drawing.Drawing2D.LineJoin.Round;

            // Add the delagate that receives pen data.
            m_tablet.onPenData += new wgssSTU.ITabletEvents2_onPenDataEventHandler(onPenData);
            m_tablet.onGetReportException += new wgssSTU.ITabletEvents2_onGetReportExceptionEventHandler(onGetReportException);

            // Initialize the screen
            clearScreen();

            // Enable the pen data on the screen (if not already)
            m_tablet.setInkingMode(0x01);
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            // You probably want to add additional processing here.
            this.sign = null;

            m_tablet.writeImage((byte)m_encodingMode, m_bitmapData);
            this.Invoke((MethodInvoker)delegate
            {
                this.Close();
            });
        }
        /**
         *
         *
         */
        public static void signPDF(DocumentData doc, String metadata, GraphSign sign, Signer signer)
        {
            ILog Log;
            Log = LogManager.GetLogger(Properties.Settings.Default.logName);
            if (!File.Exists(doc.Docsignedpath /*+ "-signed.pdf"*/))
            {
                File.Copy(doc.Docpath, doc.Docsignedpath);
            }
            try
            {
                PdfReader reader = new PdfReader(doc.Docsignedpath);
                if (File.Exists(doc.Docsignedpath + "-signed.pdf"))
                    File.Delete(doc.Docsignedpath + "-signed.pdf");
                FileStream fos = new FileStream(doc.Docsignedpath + "-signed.pdf", FileMode.CreateNew, FileAccess.Write);

                doc.Docsignedpath = doc.Docsignedpath + "-signed.pdf";
                Log.Debug(String.Format("Creating Stamper for doc {0}",doc.Docname));
                PdfStamper stp = PdfStamper.CreateSignature(reader, fos, '\0', null, true);
                Log.Debug(String.Format("Creating Certificate for doc {0}", doc.Docname));
                Org.BouncyCastle.X509.X509Certificate[] chain = crearCertificado();
                Log.Debug(String.Format("Reading private key for doc {0}", doc.Docname));
                AsymmetricKeyParameter pk = readPrivateKey();
                stp.Writer.CloseStream = false;
                LtvVerification v = stp.LtvVerification;
                //AcroFields af = stp.AcroFields;
                Log.Debug(String.Format("Adding metadata for doc {0}", doc.Docname));
                //stp.MoreInfo = metadata;
             //               foreach (String sigName in af.GetSignatureNames())
             //               {
             //                   v.AddVerification(sigName, new OcspClientBouncyCastle(), new CrlClientOffline(null), LtvVerification.CertificateOption.WHOLE_CHAIN, LtvVerification.Level.OCSP_CRL, LtvVerification.CertificateInclusion.NO);
            //                }
                PdfSignatureAppearance sap = stp.SignatureAppearance;
                //sap.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION;
                sap.Reason = metadata;
                sap.Location = "";
                sign.Image.MakeTransparent();
                sap.Image = iTextSharp.text.Image.GetInstance(sign.Image,  System.Drawing.Imaging.ImageFormat.Png);
                sap.Layer2Text = "";

                //Preserve some space for the contents
                int contentEstimated = 15000;
                Dictionary<PdfName, int> exc = new Dictionary<PdfName, int>();
                exc.Add(PdfName.CONTENTS, (contentEstimated * 2 + 2));
                //Add timestamp

                Log.Debug(String.Format("Adding timestamp for doc {0}", doc.Docname));
                TSAClientBouncyCastle tsc  = new TSAClientBouncyCastle(Properties.Settings.Default.tsaUrl, Properties.Settings.Default.tsaUser, Properties.Settings.Default.tsaPass, contentEstimated, DigestAlgorithms.SHA512);
                // Creating the signature
                //LtvTimestamp.Timestamp(sap, tsc, null);
                //Org.BouncyCastle.Crypto.BouncyCastleDigest messageDigest = MessageDigest.getInstance("SHA1");
                //IExternalDigest digest = new Org.BouncyCastle.Crypto.BouncyCastleDigest();
                //RSACryptoServiceProvider crypt = (RSACryptoServiceProvider)cert.PrivateKey;
                Log.Debug(String.Format("Dreating signature for doc {0}", doc.Docname));
                IExternalSignature signature = new PrivateKeySignature(pk, DigestAlgorithms.SHA512);
                sap.Layer2Text = "Huella: "+signature.GetHashCode();
                sap.SetVisibleSignature(new Rectangle(signer.X, signer.Y, 200, 200), signer.Page, signer.Nombre+index);
                MakeSignature.SignDetached(sap, signature, chain, null, null, tsc, 0, CryptoStandard.CMS);
                Log.Debug(String.Format("Closing file for doc {0}", doc.Docname));
                stp.Close();
                fos.Close();
                reader.Close();
            }
            catch (IOException ex)
            {
                Log.Error("IOException", ex);
            }
            catch (DocumentException dex)
            {
                Log.Error("DocumentException", dex);
            }
        }
 /**
  * @Method insert Sign Image in coordenates
  * @Params GraphSign sign biometrical graph sign
  * @Params PdfContentByte page where image will be inserted
  * @Params int x X Coordinate
  * @Params int y Y Coordinate
  * @Return true if all its OK, false if something wrong
  */
 private bool insertGraphSign(GraphSign sign,PdfContentByte page, int x, int y)
 {
     try
     {
         //sign.Image.MakeTransparent(System.Drawing.Color.White);
         //sign.Image.Save(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "test.png", System.Drawing.Imaging.ImageFormat.Png);
         Image i = Image.GetInstance((System.Drawing.Image)sign.Image, new BaseColor(System.Drawing.Color.Transparent));
         //i.BackgroundColor = BaseColor.
         float percentage = float.Parse(Properties.Settings.Default.imageRatio)/100;
         //float percentage = 0.33f;
         page.AddImage(i, i.Width*percentage, 0, 0, i.Height*percentage, x, y);
         return true;
     }
     catch (Exception ex)
     {
         //Logging exception
         Log.Error(ex.Message);
         Log.Error(ex.StackTrace);
         return false;
     }
 }
 /**
 * @Method Method that inserts the GraphSign in the pdf document and call for signing it
 * @Params DocumentData source document to be signed
 * @Params GraphSign sign Image and metadata about the Graphical Sign
 * @Params jsonSign Graphometric info JSON serialized
 * @Params signer data
 * @Return true if the document is correctly signed, false if something wrong
 */
 internal bool doSignature(DocumentData doc, GraphSign sign, String jsonSign, Signer signer, bool b)
 {
     String encrypted = jsonSign;
     return this.doSignature(doc, sign, encrypted,signer);
 }
 /**
  * @Method Method that inserts the GraphSign in the pdf document and call for signing it
  * @Params DocumentData source document to be signed
  * @Params GraphSign sign Image and metadata about the Graphical Sign
  * @Params signArray String Array with Graphometric info
  * @Params signer data
  * @Return true if the document is correctly signed, false if something wrong
  */
 internal bool doSignature(DocumentData doc, GraphSign sign, string[] signArray, Signer signer)
 {
     String encrypted ="";
     foreach (String s in signArray)
         encrypted += s;
     //this.Log.Debug("Sign String to encrypt " + encrypted);
     encrypted = DigitalSignUtils.encrypt(encrypted);
     //this.Log.Debug("Sign String encrypted " + encrypted);
     return this.doSignature(doc, sign, encrypted,signer);
 }