public void Sign2(String src, String name, String dest, X509Certificate[] chain,
                          ICipherParameters pk, String digestAlgorithm, PdfSigner.CryptoStandard subfilter,
                          String reason, String location)
        {
            PdfReader reader = new PdfReader(src);
            PdfSigner signer = new PdfSigner(reader, new FileStream(dest, FileMode.Create), new StampingProperties());

            PdfSignatureAppearance appearance = signer.GetSignatureAppearance();

            appearance.SetReason(reason);
            appearance.SetLocation(location);
            signer.SetFieldName(name);

            // Creating the appearance for layer 2
            PdfFormXObject n2 = appearance.GetLayer2();

            // Custom text, custom font, and right-to-left writing
            // Characters: لورانس العرب
            Text text = new Text("\u0644\u0648\u0631\u0627\u0646\u0633 \u0627\u0644\u0639\u0631\u0628");

            text.SetFont(PdfFontFactory.CreateFont("../../../resources/font/NotoNaskhArabic-Regular.ttf",
                                                   PdfEncodings.IDENTITY_H, true));
            text.SetBaseDirection(BaseDirection.RIGHT_TO_LEFT);
            new Canvas(n2, signer.GetDocument()).Add(new Paragraph(text).SetTextAlignment(TextAlignment.RIGHT));

            IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm);

            signer.SignDetached(pks, chain, null, null, null, 0, subfilter);
        }
Exemplo n.º 2
0
        public void Sign(String src, String name, String dest, X509Certificate[] chain,
                         ICipherParameters pk, String digestAlgorithm, PdfSigner.CryptoStandard subfilter,
                         String reason, String location)
        {
            PdfReader reader = new PdfReader(src);
            PdfSigner signer = new PdfSigner(reader, new FileStream(dest, FileMode.Create), new StampingProperties());

            // Create the signature appearance
            PdfSignatureAppearance appearance = signer.GetSignatureAppearance();

            appearance
            .SetReason(reason)
            .SetLocation(location);

            // This name corresponds to the name of the field that already exists in the document.
            signer.SetFieldName(name);

            // Get the background layer and draw a gray rectangle as a background.
            PdfFormXObject n0     = appearance.GetLayer0();
            float          x      = n0.GetBBox().ToRectangle().GetLeft();
            float          y      = n0.GetBBox().ToRectangle().GetBottom();
            float          width  = n0.GetBBox().ToRectangle().GetWidth();
            float          height = n0.GetBBox().ToRectangle().GetHeight();
            PdfCanvas      canvas = new PdfCanvas(n0, signer.GetDocument());

            canvas.SetFillColor(ColorConstants.LIGHT_GRAY);
            canvas.Rectangle(x, y, width, height);
            canvas.Fill();

            // Set the signature information on layer 2
            PdfFormXObject n2 = appearance.GetLayer2();
            Paragraph      p  = new Paragraph("This document was signed by Bruno Specimen.");

            new Canvas(n2, signer.GetDocument()).Add(p);

            IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm);

            // Sign the document using the detached mode, CMS or CAdES equivalent.
            signer.SignDetached(pks, chain, null, null, null, 0, subfilter);
        }
Exemplo n.º 3
0
        private int SignPageNr(PdfSigner signer, Signature signing)
        {
            switch (signing.SignaturePage)
            {
            case SignaturePage.CustomPage:
                if (signing.SignatureCustomPage > signer.GetDocument().GetNumberOfPages())
                {
                    return(signer.GetDocument().GetNumberOfPages());
                }
                if (signing.SignatureCustomPage < 1)
                {
                    return(1);
                }
                return(signing.SignatureCustomPage);

            case SignaturePage.LastPage:
                return(signer.GetDocument().GetNumberOfPages());

            default:
                return(1);
            }
        }
Exemplo n.º 4
0
        public void CreateSignature(String src, String dest, String fieldName,
                                    ICipherParameters pk, X509Certificate[] chain)
        {
            PdfReader reader = new PdfReader(src);

            using (FileStream os = new FileStream(dest, FileMode.Create))
            {
                PdfSigner signer = new PdfSigner(reader, os, new StampingProperties());

                IExternalSignatureContainer external = new MyExternalSignatureContainer(pk, chain);

                // Signs a PDF where space was already reserved. The field must cover the whole document.
                PdfSigner.SignDeferred(signer.GetDocument(), fieldName, os, external);
            }
        }
Exemplo n.º 5
0
        public static void CreateSignature(String src, String dest, String fieldName,
                                           ICipherParameters pk, X509Certificate[] chain)
        {
            PdfReader reader = new PdfReader(src);

            using (FileStream os = new FileStream(dest, FileMode.Create))
            {
                PdfSigner signer = new PdfSigner(reader, os, new StampingProperties());

                var signaturee = ConvertToBytes(signature);

                IExternalSignatureContainer external = new MyExternalSignatureContainer(signaturee, chain, digest);

                PdfSigner.SignDeferred(signer.GetDocument(), fieldName, os, external);
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Signing container with data retrived from web service
        /// </summary>
        /// <param name="tempPdf"></param>
        /// <param name="signedPdf"></param>
        /// <param name="signatureFieldName"></param>
        /// <param name="signature"></param>
        /// <param name="tbs"></param>
        public static void EmbedSignature(string tempPdf, string signedPdf, string signatureFieldName, string signature, string tbs)
        {
            //Convert given data from web service to bytes
            byte[] signedBytes = ConvertToBytes(signature);
            byte[] toBeSigned  = ConvertToBytes(tbs);

            using (PdfReader reader = new PdfReader(tempPdf))
            {
                using (FileStream os = File.OpenWrite(signedPdf))
                {
                    PdfSigner signer = new PdfSigner(reader, os, new StampingProperties());
                    IExternalSignatureContainer external = new MyExternalSignatureContainer(signedBytes, GetChains(), toBeSigned);
                    PdfSigner.SignDeferred(signer.GetDocument(), signatureFieldName, os, external);
                }
            }
        }
Exemplo n.º 7
0
        private static void ConfiguraAparencia(PdfSigner objStamper, CertSimples cert, int X, int Y, int Largura, int Altura, int Pagina, int Rotation, string Contact = "", string Reason = "Assinatura Digital", string Location = "Indústrias Nucleares do Brasil S/A - INB", string Creator = "Assinador da INB", TipoAssinatura Tipo = TipoAssinatura.Normal, string Cargo = "", string CREACRM = "")
        {
            PdfDocument pdfDoc = objStamper.GetDocument();
            PdfPage     oPage = pdfDoc.GetPage(Pagina);
            int         LarguraAssinatura = Largura;
            int         AlturaAssinatura = Altura;
            int         X_Ajustado, Y_Ajustado;

            X_Ajustado = X;
            Y_Ajustado = Y;
            var    crop = oPage.GetCropBox();
            float  Left, Top, Width, Height;
            Bitmap bmp            = Graphic.ConfiguraBMP(cert, out Altura, Tipo);

            if (Rotation == 270)
            {
                Left = (int)crop.GetLeft() + X_Ajustado;
                Top  = (int)crop.GetRight() - (Y_Ajustado + AlturaAssinatura + 5);
            }
            else if (Rotation == 90)
            {
                Left = (int)crop.GetRight() + X_Ajustado;
                Top  = (int)crop.GetLeft() - (Y_Ajustado + AlturaAssinatura + 5);
            }
            else
            {
                Left = (int)crop.GetLeft() + X_Ajustado;
                Top  = (int)crop.GetTop() - (Y_Ajustado + AlturaAssinatura + 5);
            }
            Width  = LarguraAssinatura;
            Height = AlturaAssinatura;
            iText.Kernel.Geom.Rectangle oRetangulo = new iText.Kernel.Geom.Rectangle(Left, Top, Width, Height);
            var pageSize          = pdfDoc.GetPage(Pagina).GetMediaBox();
            var signaturePosition = new iText.Kernel.Geom.Rectangle(pageSize.GetLeft(), pageSize.GetBottom(), pageSize.GetWidth(), pageSize.GetHeight());
            PdfSignatureAppearance signatureAppearance = objStamper.GetSignatureAppearance();
            var memoryStream = new MemoryStream();

            bmp.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            iText.IO.Image.ImageData pic = iText.IO.Image.ImageDataFactory.Create(memoryStream.ToArray());
            signatureAppearance.SetReason(Reason);
            signatureAppearance.SetLocation(Location);
            signatureAppearance.SetSignatureCreator(Creator);
            signatureAppearance.SetSignatureGraphic(pic);
            signatureAppearance.SetRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC);
            signatureAppearance.SetPageRect(oRetangulo);
            signatureAppearance.SetPageNumber(Pagina);
        }
Exemplo n.º 8
0
        public void Certify(String keystore, String src, String name, String dest)
        {
            Pkcs12Store pk12  = new Pkcs12Store(new FileStream(keystore, FileMode.Open, FileAccess.Read), PASSWORD);
            string      alias = null;

            foreach (var a in pk12.Aliases)
            {
                alias = ((string)a);
                if (pk12.IsKeyEntry(alias))
                {
                    break;
                }
            }

            ICipherParameters pk = pk12.GetKey(alias).Key;

            X509CertificateEntry[] ce    = pk12.GetCertificateChain(alias);
            X509Certificate[]      chain = new X509Certificate[ce.Length];
            for (int k = 0; k < ce.Length; ++k)
            {
                chain[k] = ce[k].Certificate;
            }

            PdfReader reader = new PdfReader(src);
            PdfSigner signer = new PdfSigner(reader, new FileStream(dest, FileMode.Create),
                                             new StampingProperties().UseAppendMode());

            // Set signer options
            signer.SetFieldName(name);
            signer.SetCertificationLevel(PdfSigner.CERTIFIED_FORM_FILLING);

            PdfAcroForm form = PdfAcroForm.GetAcroForm(signer.GetDocument(), true);

            form.GetField(name).SetReadOnly(true);

            PrivateKeySignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256);

            // Sign the document using the detached mode, CMS or CAdES equivalent.
            signer.SignDetached(pks, chain, null, null, null,
                                0, PdfSigner.CryptoStandard.CMS);
        }
Exemplo n.º 9
0
        private void SignPdf(Job job)
        {
            if (!job.Profile.PdfSettings.Signature.Enabled)
            {
                return;
            }

            ReaderProperties readerProperties = new ReaderProperties();

            if (job.Profile.PdfSettings.Security.Enabled)
            {
                readerProperties.SetPassword(Encoding.Default.GetBytes(job.Passwords.PdfOwnerPassword));
            }

            var sourceFile = job.IntermediatePdfFile;
            var targetFile = AddTailToFile(sourceFile, "_processed");

            using (PdfReader pdfReader = new PdfReader(sourceFile, readerProperties))
                using (PdfWriter pdfWriter = new PdfWriter(targetFile))
                {
                    var signer = new PdfSigner(pdfReader, pdfWriter, new StampingProperties().PreserveEncryption().UseAppendMode());
                    using (signer.GetDocument())
                    {
                        try
                        {
                            new ITextSigner().SignPdfFile(signer, job.Profile, job.Passwords, job.Accounts);
                        }
                        catch (ProcessingException)
                        {
                            throw;
                        }
                        catch (Exception ex)
                        {
                            Logger.Warn($"Could not close iText pdf stamper.\r\n{ex}");
                        }
                    }
                }

            job.IntermediatePdfFile = targetFile;
            File.Delete(sourceFile);
        }
        public virtual void SecondSignOfTaggedDocTest()
        {
            String signCertFileName = certsSrc + "signCertRsa01.p12";
            String outFileName      = destinationFolder + "secondSignOfTagged.pdf";
            String srcFileName      = sourceFolder + "taggedAndSignedDoc.pdf";

            X509Certificate[]  signChain      = Pkcs12FileHelper.ReadFirstChain(signCertFileName, password);
            ICipherParameters  signPrivateKey = Pkcs12FileHelper.ReadFirstKey(signCertFileName, password, password);
            IExternalSignature pks            = new PrivateKeySignature(signPrivateKey, DigestAlgorithms.SHA256);
            String             signatureName  = "Signature2";
            PdfSigner          signer         = new PdfSigner(new PdfReader(srcFileName), new FileStream(outFileName, FileMode.Create),
                                                              new StampingProperties().UseAppendMode());
            PdfDocument document = signer.GetDocument();

            document.GetWriter().SetCompressionLevel(CompressionConstants.NO_COMPRESSION);
            signer.SetFieldName(signatureName);
            PdfSignatureAppearance appearance = signer.GetSignatureAppearance();

            appearance.SetPageNumber(1);
            signer.GetSignatureAppearance().SetPageRect(new Rectangle(50, 550, 200, 100)).SetReason("Test2").SetLocation
                ("TestCity2").SetLayer2Text("Approval test signature #2.\nCreated by iText7.");
            signer.SignDetached(pks, signChain, null, null, null, 0, PdfSigner.CryptoStandard.CADES);
            PadesSigTest.BasicCheckSignedDoc(outFileName, "Signature1");
            PadesSigTest.BasicCheckSignedDoc(outFileName, "Signature2");
            using (PdfDocument twiceSigned = new PdfDocument(new PdfReader(outFileName))) {
                using (PdfDocument resource = new PdfDocument(new PdfReader(srcFileName))) {
                    float resourceStrElemNumber = resource.GetStructTreeRoot().GetPdfObject().GetAsArray(PdfName.K).GetAsDictionary
                                                      (0).GetAsArray(PdfName.K).Size();
                    float outStrElemNumber = twiceSigned.GetStructTreeRoot().GetPdfObject().GetAsArray(PdfName.K).GetAsDictionary
                                                 (0).GetAsArray(PdfName.K).Size();
                    // Here we assert the amount of objects in StructTreeRoot in resource file and twice signed file
                    // as the original signature validation failed by Adobe because of struct tree change. If the fix
                    // would make this tree unchanged, then the assertion should be adjusted with comparing the tree of
                    // objects in StructTreeRoot to ensure that it won't be changed.
                    NUnit.Framework.Assert.AreNotEqual(resourceStrElemNumber, outStrElemNumber);
                }
            }
        }
Exemplo n.º 11
0
        public static byte[] Sign(IExternalSignature externalSignature, X509Certificate[] certChain, string src, string friendlyName, string subject, string sourceName, string documentLink, string documentName)
        {
            int numberOfSignatures = 0;
            int numberOfPages      = 0;

            using (PdfReader reader = new PdfReader(src))
            {
                using (PdfDocument pdf = new PdfDocument(reader))
                {
                    numberOfPages = pdf.GetNumberOfPages();

                    PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf, false);
                    if (form != null)
                    {
                        foreach (var field in form.GetFormFields())
                        {
                            if (field.Value is iText.Forms.Fields.PdfSignatureFormField)
                            {
                                numberOfSignatures++;
                            }
                        }
                    }
                }
            }

            if (numberOfSignatures == 0)
            {
                string hash = GetMD5HashFromFile(src);

                src            = AddPage(src, sourceName, documentLink, documentName, hash);
                numberOfPages += 1;
            }

            float posSignY = 615 - (numberOfSignatures * 70);

            using (PdfReader reader = new PdfReader(src))
            {
                StampingProperties stampingProperties = new StampingProperties();
                stampingProperties.UseAppendMode();

                using (MemoryStream ms = new MemoryStream())
                {
                    PdfSigner signer =
                        new PdfSigner(reader, ms, stampingProperties);

                    Rectangle rect = new Rectangle(36, posSignY, 520, 65);

                    PdfSignatureAppearance appearance = signer.GetSignatureAppearance();
                    appearance
                    .SetPageRect(rect)
                    .SetPageNumber(numberOfPages)
                    .SetCertificate(certChain[0]);

                    PdfFormXObject n2     = appearance.GetLayer2();
                    Canvas         canvas = new Canvas(n2, signer.GetDocument());

                    canvas.Add(new Paragraph(friendlyName).SetMargin(0));
                    canvas.Add(new Paragraph("Assinado digitalmente por: " + friendlyName).SetFontSize(10).SetMargin(0));
                    canvas.Add(new Paragraph("Data: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss \"GMT\"zzz")).SetFontSize(10).SetMargin(0));
                    canvas.Add(new Paragraph("Subject: " + subject).SetFontSize(10).SetMargin(0));

                    signer.SignDetached(externalSignature, certChain, null, null, null, 0,
                                        PdfSigner.CryptoStandard.CADES);

                    return(ms.ToArray());
                }
            }
        }
Exemplo n.º 12
0
        public static byte[] SignPDFStream(MemoryStream source, string rootPath)
        {
            collection = new X509Certificate2Collection();
            collection.Import(GsConfig.GetSslCertificatePath(rootPath), GsConfig.KeyPassword,
                              X509KeyStorageFlags.DefaultKeySet);
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls12;

            //get JSON access token
            JObject access = Login(baseURL, GsConfig.ApiKey, GsConfig.ApiSecret);

            //get JSON with id/certificate/ocsp response
            JObject identity = Identity(baseURL, access);
            String  cert     = (String)identity.GetValue("signing_cert");
            String  id       = (String)identity.GetValue("id");
            String  oc1      = (String)identity.GetValue("ocsp_response");
            JObject path     = CertificatePath(baseURL, access);
            String  ca       = (String)path.GetValue("path");

            //Create Certificate chain
            X509Certificate[] chain = CreateChain(cert, ca);

            //create empty signature
            PdfReader reader = new PdfReader(source);

            byte[] fileArray = null;
            using (MemoryStream os = new MemoryStream()) {
                PdfSigner stamper = new PdfSigner(reader, os, new StampingProperties());

                PdfSignatureAppearance appearance = stamper.GetSignatureAppearance();
                appearance.SetPageRect(new Rectangle(0, 0, 0, 0));
                stamper.SetFieldName(fieldName);

                IExternalSignatureContainer external = new ExternalBlankSignatureContainer(PdfName.Adobe_PPKLite,
                                                                                           PdfName.Adbe_pkcs7_detached);

                stamper.SignExternalContainer(external, 8192);

                fileArray = os.ToArray();
            }

            using (var tempStream = new MemoryStream(fileArray)) {
                PdfReader tempReader = new PdfReader(tempStream);

                byte[]   oc2      = Convert.FromBase64String(oc1);
                OcspResp ocspResp = new OcspResp(oc2);

                IExternalSignatureContainer gsContainer = new MyExternalSignatureContainer(id, access, chain, ocspResp);
                using (MemoryStream destination = new MemoryStream()) {
                    PdfSigner signer = new PdfSigner(tempReader, destination, new StampingProperties());
                    PdfSigner.SignDeferred(signer.GetDocument(), fieldName, destination, gsContainer);

                    fileArray = destination.ToArray();
                }
            }

            using (MemoryStream LTV = new MemoryStream())
                using (var newSource = new MemoryStream(fileArray)) {
                    addLTVToStream(newSource, LTV, new OcspClientBouncyCastle(null),
                                   new CrlClientOnline(), LtvVerification.Level.OCSP_CRL,
                                   LtvVerification.Level.OCSP_CRL);

                    return(LTV.ToArray());
                }
        }