// This method defines the visual representation for each signature. For more information, see:
        // http://pki.lacunasoftware.com/Help/html/98095ec7-2742-4d1f-9709-681c684eb13b.htm
        private PadesVisualRepresentation2 getVisualRepresentation(PKCertificate cert)
        {
            var visualRepresentation = new PadesVisualRepresentation2()
            {
                // Text of the visual representation.
                Text = new PadesVisualText()
                {
                    // Used to compose the message.
                    CustomText = String.Format("Digitally signed by {0}", cert.SubjectName.CommonName),

                    // Specify that the signing time should also be rendered.
                    IncludeSigningTime = true,

                    // Optionally set the horizontal alignment of the text ('Left' or 'Right'), if not set the
                    // default is Left.
                    HorizontalAlign = PadesTextHorizontalAlign.Left,

                    // Optionally set the container within the signature rectangle on which to place the text. By
                    // default, the text can occupy the entire rectangle (how much of the rectangle the text will
                    // actually fill depends on the length and font size). Below, we specify that the text should
                    // respect a right margin of 1.5 cm.
                    Container = new PadesVisualRectangle()
                    {
                        Left   = 0.2,
                        Top    = 0.2,
                        Right  = 0.2,
                        Bottom = 0.2
                    }
                },
                // Background image of the visual representation.
                Image = new PadesVisualImage()
                {
                    // We'll use as background the image in Content/PdfStamp.png.
                    Content = Storage.GetPdfStampContent(),
                    // Align the image to the right.
                    HorizontalAlign = PadesHorizontalAlign.Right
                }
            };

            // Position of the visual represention. We get the footnote position preset and customize it.
            var visualPositioning = PadesVisualAutoPositioning.GetFootnote();

            visualPositioning.Container.Height              = 4.94;
            visualPositioning.SignatureRectangleSize.Width  = 8.0;
            visualPositioning.SignatureRectangleSize.Height = 4.94;
            visualRepresentation.Position = visualPositioning;

            return(visualRepresentation);
        }
        /**
         *      This method defines the visual representation for each signature. For more information, see
         *      http://pki.lacunasoftware.com/Help/html/98095ec7-2742-4d1f-9709-681c684eb13b.htm
         */
        private PadesVisualRepresentation2 getVisualRepresentation(PKCertificate cert)
        {
            // Create a visual representation.
            var visualRepresentation = new PadesVisualRepresentation2()
            {
                // Text of the visual representation.
                Text = new PadesVisualText()
                {
                    CustomText = string.Format("Signed by {0} ({1})", cert.SubjectName.CommonName, cert.PkiBrazil.CPF),
                    FontSize   = 13.0,
                    // Specify that the signing time should also be rendered.
                    IncludeSigningTime = true,
                    // Optionally set the horizontal alignment of the text ('Left' or 'Right'), if not
                    // set the default is 'Left'.
                    HorizontalAlign = PadesTextHorizontalAlign.Left,
                    // Optionally, set the container within the signature rectangle on which to place
                    // the text. By default, the text can occupy the entire rectangle (how much of the
                    // rectangle the text will actually fill depends on the length and font size).
                    // Below, we specify that text should respect a right margin of 1.5 cm.
                    Container = new PadesVisualRectangle()
                    {
                        Left   = 0.2,
                        Top    = 0.2,
                        Right  = 0.2,
                        Bottom = 0.2
                    }
                },
                Image = new PadesVisualImage()
                {
                    // We'll use as background the image in Content/PdfStamp.png.
                    Content = Storage.GetPdfStampContent(),
                    // Align the image to the right horizontally.
                    HorizontalAlign = PadesHorizontalAlign.Right,
                    // Align the image to center vertically.
                    VerticalAlign = PadesVerticalAlign.Center
                },
            };

            // Position of the visual representation. We get the footnote position preset and
            // customize it.
            var visualPositioning = PadesVisualAutoPositioning.GetFootnote();

            visualPositioning.Container.Height              = 4.94;
            visualPositioning.SignatureRectangleSize.Width  = 8.0;
            visualPositioning.SignatureRectangleSize.Height = 4.94;
            visualRepresentation.Position = visualPositioning;

            return(visualRepresentation);
        }
Exemplo n.º 3
0
        // This function is called by the PAdES samples for PKI SDK. It contains a example of signature visual
        // representation. This is only a separate function in order to organize the variaous examples.
        public PadesVisualRepresentation2 GetVisualRepresentation(PKCertificate cert)
        {
            // Create a visual representation.
            var visualRepresentation = new PadesVisualRepresentation2()
            {
                // Text of the visual representation.
                Text = new PadesVisualText()
                {
                    CustomText = String.Format("Signed by {0} ({1})", cert.SubjectDisplayName, cert.PkiBrazil.CPF),
                    FontSize   = 13.0,
                    // Specify that the signing time should also be rendered.
                    IncludeSigningTime = true,
                    // Optionally set the horizontal alignment of the text ('Left' or 'Right'), if not set the
                    // default is Left.
                    HorizontalAlign = PadesTextHorizontalAlign.Left,
                    // Optionally set the container within the signature rectangle on which to place the
                    // text. By default, the text can occupy the entire rectangle (how much of the rectangle the
                    // text will actually fill depends on the length and font size). Below, we specify that text
                    // should respect a right margin of 1.5 cm.
                    Container = new PadesVisualRectangle()
                    {
                        Left   = 0.2,
                        Top    = 0.2,
                        Right  = 0.2,
                        Bottom = 0.2
                    }
                },
                Image = new PadesVisualImage()
                {
                    // We'll use as background the image in Content/PdfStamp.png
                    Content = System.IO.File.ReadAllBytes(Path.Combine(_webHostEnvironment.ContentRootPath, "Resources", "PdfStamp.png")),
                    // Align image to the right horizontally.
                    HorizontalAlign = PadesHorizontalAlign.Right,
                    // Align image to center vertically.
                    VerticalAlign = PadesVerticalAlign.Center
                }
            };

            // Position of the visual representation. We get the footnote position preset and customize it.
            var visualPositioning = PadesVisualAutoPositioning.GetFootnote();

            visualPositioning.Container.Height              = 4.94;
            visualPositioning.SignatureRectangleSize.Width  = 8.0;
            visualPositioning.SignatureRectangleSize.Height = 4.94;
            visualRepresentation.Position = visualPositioning;

            return(visualRepresentation);
        }
Exemplo n.º 4
0
        private PadesVisualRepresentation2 getVisualRepresentation(PKCertificate signerCert)
        {
            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.Append(string.Format("Assinado digitalmente por {0} (CPF: {1})", (object)signerCert.PkiBrazil.Responsavel, (object)this.formatCpf(signerCert.PkiBrazil.CPF)));
            if (!string.IsNullOrEmpty(signerCert.PkiBrazil.Cnpj))
            {
                stringBuilder.Append(signerCert.PkiBrazil.Cnpj == CnpjMeta ? " representante da META GESTÃO DE DOCUMENTOS" : string.Format(" empresa {0}", (object)signerCert.PkiBrazil.CompanyName));
                stringBuilder.Append(string.Format(" (CNPJ: {0})", (object)this.formatCnpj(signerCert.PkiBrazil.Cnpj)));
            }
            PadesVisualRepresentation2 visualRepresentation2 = new PadesVisualRepresentation2();
            PadesVisualAutoPositioning visualAutoPositioning = new PadesVisualAutoPositioning();

            visualAutoPositioning.MeasurementUnits       = PadesMeasurementUnits.Centimeters;
            visualAutoPositioning.PageNumber             = -1;
            visualAutoPositioning.SignatureRectangleSize = new PadesSize(this.Width, this.Height);
            visualAutoPositioning.Container = new PadesVisualRectangle()
            {
                Right  = new double?(0.0),
                Left   = new double?(this.Left),
                Bottom = new double?(this.Bottom),
                Height = new double?(this.Height)
            };
            visualAutoPositioning.RowSpacing = 0.0;
            visualRepresentation2.Position   = (PadesVisualPositioning)visualAutoPositioning;
            visualRepresentation2.Text       = new PadesVisualText()
            {
                CustomText         = stringBuilder.ToString(),
                IncludeSigningTime = true,
                FontSize           = new double?(9.0),
                Container          = new PadesVisualRectangle()
                {
                    Left   = new double?(0.2),
                    Top    = new double?(0.2),
                    Right  = new double?(0.2),
                    Bottom = new double?(0.2)
                }
            };
            visualRepresentation2.Image = new PadesVisualImage()
            {
                Content = AppResources.MetaStamp_png,
            };
            return(visualRepresentation2);
        }
Exemplo n.º 5
0
        public IHttpActionResult Start(BatchSignatureStartRequest request)
        {
            byte[]             toSignBytes, transferData;
            SignatureAlgorithm signatureAlg;

            try {
                // Decode the user's certificate
                var cert = PKCertificate.Decode(request.CertContent);

                // Instantiate a PadesSigner class
                var padesSigner = new PadesSigner();

                // Set the PDF to sign, which in the case of this example is one of the batch documents
                padesSigner.SetPdfToSign(Storage.GetBatchDocContent(request.Id));

                // Set the signer certificate
                padesSigner.SetSigningCertificate(cert);

                // Set the signature policy
                padesSigner.SetPolicy(getSignaturePolicy());

                // Set the signature's visual representation options (this is optional). For more information, see
                // http://pki.lacunasoftware.com/Help/html/98095ec7-2742-4d1f-9709-681c684eb13b.htm
                var visual = new PadesVisualRepresentation2()
                {
                    // Text of the visual representation
                    Text = new PadesVisualText()
                    {
                        // Compose the message
                        CustomText = $"Assinado digitalmente por {cert.SubjectDisplayName}",

                        // Specify that the signing time should also be rendered
                        IncludeSigningTime = true,

                        // Optionally set the horizontal alignment of the text ('Left' or 'Right'), if not set the default is Left
                        HorizontalAlign = PadesTextHorizontalAlign.Left
                    },
                    // Background image of the visual representation
                    Image = new PadesVisualImage()
                    {
                        // We'll use as background the image in Content/PdfStamp.png
                        Content = Storage.GetPdfStampContent(),

                        // Opacity is an integer from 0 to 100 (0 is completely transparent, 100 is completely opaque).
                        Opacity = 50,

                        // Align the image to the right
                        HorizontalAlign = PadesHorizontalAlign.Right
                    },
                    // Set the position of the visual representation
                    Position = PadesVisualAutoPositioning.GetFootnote()
                };
                padesSigner.SetVisualRepresentation(visual);

                // Generate the "to-sign-bytes". This method also yields the signature algorithm that must
                // be used on the client-side, based on the signature policy, as well as the "transfer data",
                // a byte-array that will be needed on the next step.
                toSignBytes = padesSigner.GetToSignBytes(out signatureAlg, out transferData);
            } catch (ValidationException ex) {
                // Some of the operations above may throw a ValidationException, for instance if the certificate
                // encoding cannot be read or if the certificate is expired.
                var message = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.ValidationResults.ToString());
                return(ResponseMessage(message));
            }

            // For the next steps, we'll need once again some information:
            // - The "transfer data" filename. Its content is stored in a temporary file (with extension .bin) to
            // be shared with the Complete action.
            // - The "to-sign-hash" (digest of the "to-sign-bytes"). And the OID of the digest algorithm to be
            // used during the signature operation. this information is need in the signature computation with
            // Web PKI component. (see batch-signature-form.js)
            return(Ok(new BatchSignatureStartResponse()
            {
                TransferDataFileId = Storage.StoreFile(transferData, ".bin"),
                ToSignHash = signatureAlg.DigestAlgorithm.ComputeHash(toSignBytes),
                DigestAlgorithmOid = signatureAlg.DigestAlgorithm.Oid
            }));
        }
Exemplo n.º 6
0
        private static bool SignFile(string file, PKCertificateWithKey certWithKey, PadesPolicySpec policy, PadesVisualRepresentation2 visual, Metadata metadata, string outputDir, string outputName = null)
        {
            var documentoToSign = File.ReadAllBytes(file);

            if (metadata != null)
            {
                using (var buffer = new MemoryStream())
                {
                    using (var stream = new MemoryStream(documentoToSign))
                    {
                        DoConvertToPdfA(stream, metadata, buffer);
                    }
                    documentoToSign = buffer.ToArray();
                }
            }

            var signer = new PadesSigner();

            signer.SetSigningCertificate(certWithKey);
            signer.SetPdfToSign(documentoToSign);
            signer.SetPolicy(policy);
            signer.SetVisualRepresentation(visual);
            signer.SetCertificateValidationConfigurator(ConfigureNoValidation);
            if (string.IsNullOrWhiteSpace(outputName))
            {
                outputName = Path.GetFileName(file);
            }
            try {
                signer.ComputeSignature();
                var signed = signer.GetPadesSignature();
                File.WriteAllBytes(Path.Combine(outputDir, outputName), signed);
            } catch (Exception exception) {
                Log(exception.ToString(), file);
                return(false);
            }
            return(true);
        }
        public ActionResult Index(SignatureStartModel model)
        {
            byte[]             toSignBytes, transferData;
            SignatureAlgorithm signatureAlg;

            try {
                // Decode the user's certificate
                var cert = PKCertificate.Decode(model.CertContent);

                // Instantiate a PadesSigner class
                var padesSigner = new PadesSigner();

                // Set the PDF to sign, which in the case of this example is a fixed sample document
                padesSigner.SetPdfToSign(Storage.GetSampleDocContent());

                // Set the signer certificate
                padesSigner.SetSigningCertificate(cert);

                // Set the signature policy
                padesSigner.SetPolicy(getSignaturePolicy());

                // Set the signature's visual representation options (this is optional). For more information, see
                // http://pki.lacunasoftware.com/Help/html/98095ec7-2742-4d1f-9709-681c684eb13b.htm
                var visual = new PadesVisualRepresentation2()
                {
                    // Text of the visual representation
                    Text = new PadesVisualText()
                    {
                        // Compose the message
                        CustomText = String.Format("Assinado digitalmente por {0}", cert.SubjectDisplayName),

                        // Specify that the signing time should also be rendered
                        IncludeSigningTime = true,

                        // Optionally set the horizontal alignment of the text ('Left' or 'Right'), if not set the default is Left
                        HorizontalAlign = PadesTextHorizontalAlign.Left
                    },
                    // Background image of the visual representation
                    Image = new PadesVisualImage()
                    {
                        // We'll use as background the image in Content/PdfStamp.png
                        Content = Storage.GetPdfStampContent(),

                        // Opacity is an integer from 0 to 100 (0 is completely transparent, 100 is completely opaque).
                        Opacity = 50,

                        // Align the image to the right
                        HorizontalAlign = PadesHorizontalAlign.Right
                    },
                    // Set the position of the visual representation
                    Position = PadesVisualAutoPositioning.GetFootnote()
                };
                padesSigner.SetVisualRepresentation(visual);

                // Generate the "to-sign-bytes". This method also yields the signature algorithm that must
                // be used on the client-side, based on the signature policy, as well as the "transfer data",
                // a byte-array that will be needed on the next step.
                toSignBytes = padesSigner.GetToSignBytes(out signatureAlg, out transferData);
            } catch (ValidationException ex) {
                // Some of the operations above may throw a ValidationException, for instance if the certificate
                // encoding cannot be read or if the certificate is expired.
                ModelState.AddModelError("", ex.ValidationResults.ToString());
                return(View());
            }

            // On the next step (Complete action), we'll need once again some information:
            // - The content of the selected certificate only used to render the user's certificate information
            //  after the signature is completed. It is no longer needed for the signature process.
            // - The thumbprint of the selected certificate.
            // - The "transfer data" used to validate the signature in complete action.
            // - The "to-sign-hash" (digest of the "to-sign-bytes") to be signed. (see signature-complete-form.js)
            // - The OID of the digest algorithm to be used during the signature operation.
            // We'll store these values on TempData, which is a dictionary shared between actions.
            TempData["SignatureCompleteModel"] = new SignatureCompleteModel()
            {
                CertContent        = model.CertContent,
                CertThumb          = model.CertThumb,
                TransferData       = transferData,
                ToSignHash         = signatureAlg.DigestAlgorithm.ComputeHash(toSignBytes),
                DigestAlgorithmOid = signatureAlg.DigestAlgorithm.Oid
            };

            return(RedirectToAction("Complete"));
        }