public static async Task SignPdfFile(String accessToken, String credentialId, String pin, String otp, String inPath, String outPath)
        {
            try
            {
                PdfReader reader = new PdfReader(inPath);
                PdfSigner signer = new PdfSigner(reader, new FileStream(outPath, FileMode.Create), new StampingProperties());

                PdfSignatureAppearance appearance = signer.GetSignatureAppearance()
                                                    .SetReason("Test semnatura digitala")
                                                    .SetLocation("Bucuresti, RO")

                                                    .SetReuseAppearance(false);
                Rectangle rect = new Rectangle(300, 690, 200, 100);
                appearance.SetPageRect(rect).SetPageNumber(1);
                signer.SetFieldName("semnatura iText7");

                IExternalSignature pks = new CSCPAdESSignature(accessToken, credentialId, pin, otp);

                X509Certificate[] chain = await CSC_API_Utils.GetCertChainAsync(accessToken, credentialId);

                ICrlClient signingCertCrl = new CrlClientOnline(chain);

                List <ICrlClient> crlList = new List <ICrlClient>();
                crlList.Add(signingCertCrl);
                ITSAClient tsaClient = new TSAClientBouncyCastle("http://timestamp.globalsign.com/scripts/timestamp.dll");


                signer.SignDetached(pks, chain, crlList, null, tsaClient, 0, PdfSigner.CryptoStandard.CADES);
            }
            catch (Exception e)
            {
                logger.Error(e.Message);
            }
        }
        public virtual void SignEncryptedDoc01()
        {
            String fileName  = "encrypted.pdf";
            String src       = sourceFolder + fileName;
            String dest      = destinationFolder + "signed_" + fileName;
            String fieldName = "Signature1";

            byte[]    ownerPass = "******".GetBytes();
            PdfReader reader    = new PdfReader(src, new ReaderProperties().SetPassword(ownerPass));
            PdfSigner signer    = new PdfSigner(reader, new FileStream(dest, FileMode.Create), new StampingProperties().UseAppendMode
                                                    ());
            // Creating the appearance
            PdfSignatureAppearance appearance = signer.GetSignatureAppearance().SetReason("Test1").SetLocation("TestCity"
                                                                                                               );

            signer.SetFieldName(fieldName);
            // Creating the signature
            IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256);

            signer.SignDetached(pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES);
            LtvVerifier verifier = new LtvVerifier(new PdfDocument(new PdfReader(dest, new ReaderProperties().SetPassword
                                                                                     (ownerPass))));

            verifier.SetVerifyRootCertificate(false);
            verifier.Verify(null);
        }
示例#3
0
        public static async Task SignPdfFileAsync(String accessToken, String credentialId, String pin, String otp, String inPath, String outPath)
        {
            try
            {
                PdfReader reader = new PdfReader(inPath);
                PdfSigner signer = new PdfSigner(reader, new FileStream(outPath, FileMode.Create), false);

                PdfSignatureAppearance appearance = signer.GetSignatureAppearance()
                                                    .SetReason("Reason")
                                                    .SetLocation("Romania")
                                                    .SetReuseAppearance(false);
                Rectangle rect = new Rectangle(36, 648, 200, 100);
                appearance.SetPageRect(rect).SetPageNumber(1);
                signer.SetFieldName("sig");

                IExternalSignature pks = new CSCPAdESSignature(accessToken, credentialId, pin, otp);

                X509Certificate [] chain = await CSC_API_Utils.GetCertChainAsync(accessToken, credentialId);

                ICrlClient signingCertCrl = new CrlClientOnline(chain);

                List <ICrlClient> crlList = new List <ICrlClient>();
                crlList.Add(signingCertCrl);

                signer.SignDetached(pks, chain, crlList, null, null, 0, PdfSigner.CryptoStandard.CADES);
            }
            catch (Exception e)
            {
            }
        }
        public void Sign(String src, String dest, X509Certificate[] chain, ICipherParameters pk,
                         String digestAlgorithm, PdfSigner.CryptoStandard subfilter, String reason, String location,
                         ICollection <ICrlClient> crlList, IOcspClient ocspClient, ITSAClient tsaClient, int estimatedSize)
        {
            PdfReader reader = new PdfReader(src);
            PdfSigner signer = new PdfSigner(reader, new FileStream(dest, FileMode.Create), new StampingProperties());

            // Create the signature appearance
            Rectangle rect = new Rectangle(36, 648, 200, 100);
            PdfSignatureAppearance appearance = signer.GetSignatureAppearance();

            appearance
            .SetReason(reason)
            .SetLocation(location)

            // Specify if the appearance before field is signed will be used
            // as a background for the signed field. The "false" value is the default value.
            .SetReuseAppearance(false)
            .SetPageRect(rect)
            .SetPageNumber(1);
            signer.SetFieldName("sig");

            IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm);

            // Sign the document using the detached mode, CMS or CAdES equivalent.
            // Pass the created TSAClient to the signing method.
            signer.SignDetached(pks, chain, crlList, ocspClient, tsaClient, estimatedSize, subfilter);
        }
        /// <exception cref="Org.BouncyCastle.Security.GeneralSecurityException"/>
        /// <exception cref="System.IO.IOException"/>
        protected internal virtual void Sign(String src, String name, String dest, X509Certificate[] chain, ICipherParameters
                                             pk, String digestAlgorithm, PdfSigner.CryptoStandard subfilter, String reason, String location, Rectangle
                                             rectangleForNewField, bool setReuseAppearance, bool isAppendMode, int certificationLevel, float?fontSize
                                             )
        {
            PdfReader          reader     = new PdfReader(src);
            StampingProperties properties = new StampingProperties();

            if (isAppendMode)
            {
                properties.UseAppendMode();
            }
            PdfSigner signer = new PdfSigner(reader, new FileStream(dest, FileMode.Create), properties);

            signer.SetCertificationLevel(certificationLevel);
            // Creating the appearance
            PdfSignatureAppearance appearance = signer.GetSignatureAppearance().SetReason(reason).SetLocation(location
                                                                                                              ).SetReuseAppearance(setReuseAppearance);

            if (rectangleForNewField != null)
            {
                appearance.SetPageRect(rectangleForNewField);
            }
            if (fontSize != null)
            {
                appearance.SetLayer2FontSize((float)fontSize);
            }
            signer.SetFieldName(name);
            // Creating the signature
            IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm);

            signer.SignDetached(pks, chain, null, null, null, 0, subfilter);
        }
        public void Sign1(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);

            // Set the custom text and a custom font
            appearance.SetLayer2Text("This document was signed by Bruno Specimen");
            appearance.SetLayer2Font(PdfFontFactory.CreateFont(StandardFonts.TIMES_ROMAN));

            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);
        }
        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);
        }
示例#8
0
        public void Sign(String src, String dest, X509Certificate[] chain, ICipherParameters pk,
                         String digestAlgorithm, PdfSigner.CryptoStandard subfilter,
                         int certificationLevel, 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);
            appearance.SetLocation(location);

            Rectangle rect = new Rectangle(36, 648, 200, 100);

            appearance.SetPageRect(rect).SetPageNumber(1);
            signer.SetFieldName("sig");

            /* Set the document's certification level. This parameter defines if changes are allowed
             * after the applying of the signature.
             */
            signer.SetCertificationLevel(certificationLevel);

            PrivateKeySignature 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);
        }
示例#9
0
        public void Sign(String src, String tmp, String dest, X509Certificate[] chain,
                         ICipherParameters pk, String digestAlgorithm, PdfSigner.CryptoStandard subfilter,
                         String reason, String location)
        {
            PdfReader reader = new PdfReader(src);

            // Pass the temporary file's path to the PdfSigner constructor
            PdfSigner signer = new PdfSigner(reader, new FileStream(dest, FileMode.Create), tmp,
                                             new StampingProperties());

            // Create the signature appearance
            Rectangle rect = new Rectangle(36, 648, 200, 100);
            PdfSignatureAppearance appearance = signer.GetSignatureAppearance();

            appearance
            .SetReason(reason)
            .SetLocation(location)

            // Specify if the appearance before field is signed will be used
            // as a background for the signed field. The "false" value is the default value.
            .SetReuseAppearance(false)
            .SetPageRect(rect)
            .SetPageNumber(1);
            signer.SetFieldName("sig");

            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);
        }
        public void Sign(String src, String name, String dest, X509Certificate[] chain,
                         ICipherParameters pk, String digestAlgorithm, PdfSigner.CryptoStandard subfilter,
                         String reason, String location, PdfSignatureAppearance.RenderingMode renderingMode, ImageData image)
        {
            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);
            appearance.SetLocation(location);

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

            appearance.SetLayer2Text("Signed on " + DateTime.Now);

            // Set the rendering mode for this signature.
            appearance.SetRenderingMode(renderingMode);

            // Set the Image object to render when the rendering mode is set to RenderingMode.GRAPHIC
            // or RenderingMode.GRAPHIC_AND_DESCRIPTION.
            appearance.SetSignatureGraphic(image);

            PrivateKeySignature 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);
        }
示例#11
0
        /// <exception cref="System.IO.IOException"/>
        /// <exception cref="Org.BouncyCastle.Security.GeneralSecurityException"/>
        /// <exception cref="System.Exception"/>
        private void TestSignatureOnRotatedPage(int pageNum, PdfSignatureAppearance.RenderingMode renderingMode, StringBuilder
                                                assertionResults)
        {
            String    fileName = "signaturesOnRotatedPages" + pageNum + "_mode_" + renderingMode.ToString() + ".pdf";
            String    src      = sourceFolder + "documentWithRotatedPages.pdf";
            String    dest     = destinationFolder + fileName;
            PdfSigner signer   = new PdfSigner(new PdfReader(src), new FileStream(dest, FileMode.Create), new StampingProperties
                                                   ().UseAppendMode());
            PdfSignatureAppearance appearance = signer.GetSignatureAppearance();

            appearance.SetLayer2Text("Digitally signed by Test User. All rights reserved. Take care!").SetPageRect(new
                                                                                                                   Rectangle(100, 100, 100, 50)).SetRenderingMode(renderingMode).SetSignatureGraphic(ImageDataFactory.Create
                                                                                                                                                                                                         (sourceFolder + "itext.png")).SetPageNumber(pageNum);
            signer.SetCertificationLevel(PdfSigner.NOT_CERTIFIED);
            IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256);

            signer.SignDetached(pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES);
            // Make sure iText can open the document
            new PdfDocument(new PdfReader(dest)).Close();
            try {
                String testResult = new CompareTool().CompareVisually(dest, sourceFolder + "cmp_" + fileName, destinationFolder
                                                                      , "diff_");
                if (null != testResult)
                {
                    assertionResults.Append(testResult);
                }
            }
            catch (CompareTool.CompareToolExecutionException e) {
                assertionResults.Append(e.Message);
            }
        }
示例#12
0
        public static void Sign(string fileName, string signedFileName, string reason, string location,
                                string privateKeyFileName, string certFileName, string password)
        {
            PdfReader reader = new PdfReader(fileName);
            PdfWriter write  = new PdfWriter(signedFileName);
            PdfSigner signer = new PdfSigner(reader, write, false);

            PdfSignatureAppearance appearance = signer.GetSignatureAppearance();

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

            Rectangle rect = new Rectangle(36, 648, 200, 100);

            appearance.SetPageRect(rect);
            appearance.SetPageNumber(1);

            signer.SetFieldName("sig");

            IExternalSignature pks = new PrivateKeySignature(ReadPrivateKey(privateKeyFileName, password), GetEncryptionAlgorithm());

            X509CertificateParser parser = new X509CertificateParser();
            X509Certificate       cert   = LoadCertificate(certFileName);

            X509Certificate[] chain = new X509Certificate[1];
            chain[0] = cert;
            PdfSigner.CryptoStandard subfilter = GetSubFilter();

            signer.SignDetached(pks, chain, null, null, null, 0, subfilter);
        }
示例#13
0
        public static void Sign(string input, string output, ImageData stamper, ICipherParameters privateKey, X509Certificate[] chain, string flag)
        {
            PdfDocument document = new PdfDocument(new PdfReader(input));

            PdfAcroForm acroForm = PdfAcroForm.GetAcroForm(document, false);
            bool        append   = (acroForm != null && acroForm.GetSignatureFlags() != 0);

            int pageNumber = document.GetNumberOfPages();

            RegexBasedLocationExtractionStrategy strategy = new RegexBasedLocationExtractionStrategy(flag);
            PdfDocumentContentParser             parser   = new PdfDocumentContentParser(document);

            parser.ProcessContent(pageNumber, strategy);
            var locations = new List <IPdfTextLocation>(strategy.GetResultantLocations());

            document.Close();

            StampingProperties properties = new StampingProperties();

            properties = append ? properties.UseAppendMode() : properties;

            PdfSigner signer = new PdfSigner(new PdfReader(input), new FileStream(output, FileMode.Create), properties);

            signer.SetCertificationLevel(PdfSigner.CERTIFIED_NO_CHANGES_ALLOWED);

            PdfSignatureAppearance appearance = signer.GetSignatureAppearance();

            appearance.SetPageNumber(pageNumber);

            int size = locations.Count;

            if (size != 0)
            {
                IPdfTextLocation location = locations[size - 1];

                float flagX = location.GetRectangle().GetX();
                float flagY = location.GetRectangle().GetY();

                float width  = stamper.GetWidth();
                float height = stamper.GetHeight();

                float x = flagX - width / 2;
                float y = flagY - height / 2;

                appearance.SetRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC);
                appearance.SetSignatureGraphic(stamper);
                appearance.SetPageRect(new Rectangle(x, y, width, height));
            }

            PrivateKeySignature signature = new PrivateKeySignature(privateKey, DigestAlgorithms.SHA256);

            signer.SignDetached(signature, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES);
        }
示例#14
0
        static void Main(string[] args)
        {
            Parser.Default.ParseArguments <Options>(args).WithParsed <Options>(options =>
            {
                string keystore = options.SignatureCertificate;
                char[] password = options.SignaturePassword.ToCharArray();

                Pkcs12Store pkcs12Store = new Pkcs12Store(new FileStream(keystore, FileMode.Open, FileAccess.Read), password);
                string keyAlias         = null;

                foreach (object alias in pkcs12Store.Aliases)
                {
                    keyAlias = (string)alias;

                    if (pkcs12Store.IsKeyEntry(keyAlias))
                    {
                        break;
                    }
                }

                ICipherParameters key = pkcs12Store.GetKey(keyAlias).Key;

                X509CertificateEntry[] certificateEntry = pkcs12Store.GetCertificateChain(keyAlias);
                X509Certificate[] certificate           = new X509Certificate[certificateEntry.Length];

                for (int i = 0; i < certificateEntry.Length; ++i)
                {
                    certificate[i] = certificateEntry[i].Certificate;
                }

                string srcPdf  = options.SrcPdf;
                string destPdf = System.IO.Path.GetTempFileName();

                PdfReader pdfReader = new PdfReader(srcPdf);
                PdfSigner pdfSigner = new PdfSigner(pdfReader, new FileStream(destPdf, FileMode.Create), new StampingProperties());

                PdfSignatureAppearance appearance = pdfSigner.GetSignatureAppearance();

                appearance
                .SetLayer2Text(options.SignatureText)
                .SetPageRect(new Rectangle(options.SignatureRectangleX, options.SignatureRectangleY, options.SignatureRectangleWidth, options.SignatureRectangleHeight))
                .SetPageNumber(1);

                pdfSigner.SetFieldName(options.SignatureName);

                IExternalSignature privateKeySignature = new PrivateKeySignature(key, DigestAlgorithms.SHA256);

                pdfSigner.SignDetached(privateKeySignature, certificate, null, null, null, 0, PdfSigner.CryptoStandard.CMS);

                Console.WriteLine(destPdf);
            });
        }
        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);
                }
            }
        }
示例#16
0
        public async Task <byte[]> Sign(byte[] source, SigningProperties signingProperties)
        {
            using (var inputStream = new MemoryStream(source))
                using (var reader = new PdfReader(inputStream))
                    using (var outputStream = new MemoryStream())
                    {
                        var stampProps = new StampingProperties();
                        var signer     = new PdfSigner(reader, outputStream, stampProps);

                        signer.SetCertificationLevel(PdfSigner.CERTIFIED_NO_CHANGES_ALLOWED);

                        var sap = signer.GetSignatureAppearance();

                        sap.SetLocation(signingProperties.Location);
                        sap.SetReason(signingProperties.Reason);
                        sap.SetReuseAppearance(false);

                        var certData = await s3Repository.GetDocument(signingProperties.Bucket, signingProperties.Key);

                        // code from https://stackoverflow.com/questions/12470498/how-to-read-the-pfx-file
                        using (var keyStream = new MemoryStream(certData))
                        {
                            var passphrase = signingProperties.Password;

                            if (signingProperties.KMSData != null)
                            {
                                // key is encrypted with KSM
                                var key = await kSMRepository.GetKey(signingProperties.KMSData);

                                passphrase = kSMRepository.DecryptData(passphrase, key);
                            }

                            var store = new Pkcs12Store(keyStream, signingProperties.Password.ToCharArray());

                            string alias = store.Aliases.OfType <string>().First(x => store.IsKeyEntry(x));

                            var privateKey = store.GetKey(alias).Key;

                            var keyChain = store.GetCertificateChain(alias)
                                           .Select(x => x.Certificate).ToArray();

                            IExternalSignature externalSignature = new PrivateKeySignature(privateKey, DigestAlgorithms.SHA256);

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

                            return(outputStream.ToArray());
                        }
                    }
        }
        /// <exception cref="System.IO.IOException"/>
        /// <exception cref="Org.BouncyCastle.Security.GeneralSecurityException"/>
        private void TestSignatureAppearanceAutoscale(String dest, Rectangle rect, PdfSignatureAppearance.RenderingMode
                                                      renderingMode)
        {
            String    src    = sourceFolder + "simpleDocument.pdf";
            PdfSigner signer = new PdfSigner(new PdfReader(src), new FileStream(dest, FileMode.Create), false);

            // Creating the appearance
            signer.GetSignatureAppearance().SetLayer2FontSize(0).SetReason("Test 1").SetLocation("TestCity").SetPageRect
                (rect).SetRenderingMode(renderingMode).SetSignatureGraphic(ImageDataFactory.Create(sourceFolder + "itext.png"
                                                                                                   ));
            signer.SetFieldName("Signature1");
            // Creating the signature
            IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256);

            signer.SignDetached(pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES);
        }
示例#18
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);
        }
示例#19
0
        public virtual void CalcHashOnDocCreationThenDeferredSignTest01()
        {
            String input       = sourceFolder + "helloWorldDoc.pdf";
            String outFileName = destinationFolder + "calcHashOnDocCreationThenDeferredSignTest01.pdf";
            String cmpFileName = sourceFolder + "cmp_calcHashOnDocCreationThenDeferredSignTest01.pdf";
            // pre-calculate hash on creating pre-signed PDF
            String       sigFieldName  = "DeferredSignature1";
            PdfName      filter        = PdfName.Adobe_PPKLite;
            PdfName      subFilter     = PdfName.Adbe_pkcs7_detached;
            int          estimatedSize = 8192;
            PdfReader    reader        = new PdfReader(input);
            MemoryStream baos          = new MemoryStream();
            PdfSigner    signer        = new PdfSigner(reader, baos, new StampingProperties());

            signer.SetCertificationLevel(PdfSigner.CERTIFIED_NO_CHANGES_ALLOWED);
            PdfSignatureAppearance appearance = signer.GetSignatureAppearance();

            appearance.SetLayer2Text("Signature field which signing is deferred.").SetPageRect(new Rectangle(36, 600,
                                                                                                             200, 100)).SetPageNumber(1);
            signer.SetFieldName(sigFieldName);
            SignDeferredTest.DigestCalcBlankSigner external = new SignDeferredTest.DigestCalcBlankSigner(filter, subFilter
                                                                                                         );
            signer.SignExternalContainer(external, estimatedSize);
            byte[] docBytesHash   = external.GetDocBytesHash();
            byte[] preSignedBytes = baos.ToArray();
            // sign the hash
            String signCertFileName = certsSrc + "signCertRsa01.p12";

            X509Certificate[] signChain      = Pkcs12FileHelper.ReadFirstChain(signCertFileName, password);
            ICipherParameters signPrivateKey = Pkcs12FileHelper.ReadFirstKey(signCertFileName, password, password);

            byte[] cmsSignature = SignDocBytesHash(docBytesHash, signPrivateKey, signChain);
            // fill the signature to the presigned document
            SignDeferredTest.ReadySignatureSigner extSigContainer = new SignDeferredTest.ReadySignatureSigner(cmsSignature
                                                                                                              );
            PdfDocument docToSign = new PdfDocument(new PdfReader(new MemoryStream(preSignedBytes)));
            FileStream  outStream = new FileStream(outFileName, FileMode.Create);

            PdfSigner.SignDeferred(docToSign, sigFieldName, outStream, extSigContainer);
            docToSign.Close();
            outStream.Dispose();
            // validate result
            PadesSigTest.BasicCheckSignedDoc(outFileName, sigFieldName);
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareVisually(outFileName, cmpFileName, destinationFolder
                                                                            , null));
        }
示例#20
0
        public void SignDocument(SigningDocument signingDocument)
        {
            string KEYSTORE = $"{signingDocument.CertificatDestination}";

            char[] PASSWORD = $"{signingDocument.Password}".ToCharArray();

            Pkcs12Store pk12 = new Pkcs12Store(new FileStream(KEYSTORE,
                                                              FileMode.Open, FileAccess.Read), PASSWORD);
            string alias = null;

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

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

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

            var    f    = signingDocument.File.OpenReadStream();
            string DEST = $"{signingDocument.destinationSave}\\Signed{signingDocument.File.FileName}";

            PdfReader p      = new PdfReader(f);
            PdfSigner signer = new PdfSigner(p, new FileStream(DEST, FileMode.Create),
                                             new StampingProperties());

            PdfSignatureAppearance appearance = signer.GetSignatureAppearance();

            appearance.SetLocation(signingDocument.Location)
            .SetPageRect(new Rectangle(425, 0, 150, 75))
            .SetPageNumber(1);
            signer.SetFieldName("MyFieldName");

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

            signer.SignDetached(pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CMS);
        }
        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
            signer.GetSignatureAppearance()
            .SetReason(reason)
            .SetLocation(location);
            signer.SetFieldName(name);

            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);
        }
        /// <summary>
        /// Electronically signs the PDF of agreement report.
        /// </summary>
        /// <param name="id">Employee's ID.</param>
        /// <param name="pfxPath">Path of PFX file.</param>
        /// <param name="password">Password to open PFX.</param>
        public static void SignPDF(int id, string pfxPath, char[] password)
        {
            ICipherParameters privateKey;

            X509Certificate[] chain;
            using (var fileStream = new FileStream(pfxPath, FileMode.Open, FileAccess.Read)) {
                var    pk12  = new Pkcs12Store(fileStream, password);
                string alias = null;
                foreach (object a in pk12.Aliases)
                {
                    alias = a as string;
                    if (pk12.IsKeyEntry(alias))
                    {
                        break;
                    }
                }
                privateKey = pk12.GetKey(alias).Key;

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

            using (var reader = new PdfReader(ReportGenerator.GetReportPath(id)))
                using (var fileStream = new FileStream(ReportGenerator.GetReportPath(id, "_SIGNED"), FileMode.Create)) {
                    var signer = new PdfSigner(reader, fileStream, new StampingProperties());
                    int lastPage;
                    using (var r = new PdfReader(ReportGenerator.GetReportPath(id)))
                        using (var document = new PdfDocument(r)) {
                            lastPage = document.GetNumberOfPages();
                        }
                    var appearance = signer.GetSignatureAppearance()
                                     .SetReason("Me comprometo al uso responsable del software especificado en este documento.")
                                     .SetPageRect(new Rectangle(100, 1000, 200, 100))
                                     .SetPageNumber(lastPage);
                    signer.SetFieldName("MyFieldName");

                    var pks = new PrivateKeySignature(privateKey, DigestAlgorithms.SHA256);
                    signer.SignDetached(pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CMS);
                }
        }
        public virtual void SequentialSignOfFileWithAnnots()
        {
            String signCertFileName = certsSrc + "signCertRsa01.p12";
            String outFileName      = destinationFolder + "sequentialSignOfFileWithAnnots.pdf";
            String srcFileName      = sourceFolder + "signedWithAnnots.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());

            signer.SetFieldName(signatureName);
            signer.GetSignatureAppearance().SetPageRect(new Rectangle(50, 350, 200, 100)).SetReason("Test").SetLocation
                ("TestCity").SetLayer2Text("Approval test signature.\nCreated by iText7.");
            signer.SignDetached(pks, signChain, null, null, null, 0, PdfSigner.CryptoStandard.CADES);
            PadesSigTest.BasicCheckSignedDoc(outFileName, signatureName);
        }
示例#24
0
        public static byte[] EmptySignature()
        {
            byte[] Hash = null;

            PdfReader reader = new PdfReader(src);

            using (FileStream fout = new FileStream(temp, FileMode.Create))
            {
                StampingProperties sp = new StampingProperties();
                sp.UseAppendMode();

                PdfSigner pdfSigner = new PdfSigner(reader, fout, sp);
                pdfSigner.SetFieldName("Signature");

                PdfSignatureAppearance appearance = pdfSigner.GetSignatureAppearance();
                appearance.SetPageNumber(1);
                appearance.SetPageRect(new Rectangle(100, 100));
                appearance.SetLocation("Varazdin");

                SHA256 sha           = new SHA256CryptoServiceProvider();
                String hashAlgorithm = DigestAlgorithms.SHA256;

                var externalSignature = new ExternalHashingSignatureContainer(PdfName.Adobe_PPKLite,
                                                                              PdfName.Adbe_pkcs7_detached);
                pdfSigner.SignExternalContainer(externalSignature, 8192);
                digest = externalSignature.Hash;

                var base64digest = Convert.ToBase64String(digest);
            }

            PdfReader  readerFout       = new PdfReader(temp);
            FileStream destPdf          = new FileStream(dest, FileMode.Create);
            PdfSigner  pdfSigner2       = new PdfSigner(readerFout, destPdf, new StampingProperties());
            var        hashBase65       = Convert.ToBase64String(digest);
            string     signedBase64Hash = String.Empty;

            byte[] signedHash = ConvertToBytes(signedBase64Hash);
            var    container  = new MyExternalSignatureContainer(signedHash, GetChains(), Hash);

            pdfSigner2.SignExternalContainer(container, 8192);

            return(Hash);
        }
示例#25
0
        private static void _addCarimbo(AssinarDTO dadosAssinatura, X509Certificate[] chain, PdfSigner signer)
        {
            PdfSignatureAppearance appearance = signer.GetSignatureAppearance();
            var informacoesCertificado        = chain.First().SubjectDN.GetValueList();
            var assinante    = informacoesCertificado[informacoesCertificado.Count - 1];
            var textoCarimbo = $"Assinado digitalmente por: {assinante}. \n" +
                               $"Em: {dadosAssinatura.Local}. \n" +
                               $"Na data de: {DateTime.Now:dd/MM/yyyy} as {DateTime.Now:HH:mm}. \n" +
                               $"Razão: {dadosAssinatura.Razao}.";

            appearance.SetLayer2Text(textoCarimbo)
            .SetPageRect(new Rectangle(dadosAssinatura.GetPosicao().X, dadosAssinatura.GetPosicao().Y, dadosAssinatura.GetTamanho().X, dadosAssinatura.GetTamanho().Y))
            .SetLocation(dadosAssinatura.Local)
            .SetReason(dadosAssinatura.Razao)
            .SetSignatureCreator("SGI Digital Signature")
            .SetPageNumber(1)
            ;
            signer.SetFieldName("Campo de assinatura");
        }
示例#26
0
        public virtual void FontColorTest01()
        {
            String    fileName = "fontColorTest01.pdf";
            String    dest     = destinationFolder + fileName;
            Rectangle rect     = new Rectangle(36, 648, 100, 50);
            String    src      = sourceFolder + "simpleDocument.pdf";
            PdfSigner signer   = new PdfSigner(new PdfReader(src), new FileStream(dest, FileMode.Create), new StampingProperties
                                                   ());

            // Creating the appearance
            signer.GetSignatureAppearance().SetLayer2FontColor(ColorConstants.RED).SetLayer2Text("Verified and signed by me."
                                                                                                 ).SetPageRect(rect);
            signer.SetFieldName("Signature1");
            // Creating the signature
            IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256);

            signer.SignDetached(pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES);
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareVisually(dest, sourceFolder + "cmp_" + fileName, destinationFolder
                                                                            , "diff_"));
        }
示例#27
0
        public void SignAgain(String src, 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().UseAppendMode());

            PdfSignatureAppearance appearance = signer.GetSignatureAppearance();

            appearance.SetReason(reason);
            appearance.SetLocation(location);
            appearance.SetReuseAppearance(false);
            Rectangle rect = new Rectangle(36, 700, 200, 100);

            appearance.SetPageRect(rect).SetPageNumber(1);
            signer.SetFieldName("Signature2");

            PrivateKeySignature pks = new PrivateKeySignature(pk, digestAlgorithm);

            signer.SignDetached(pks, chain, null, null, null, 0, subfilter);
        }
示例#28
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);
        }
示例#29
0
        protected void SignDocumentSignature(string filePath, ElectronicSignatureInfoDTO signatureInfo)
        {
            PdfSigner pdfSigner = new PdfSigner(new PdfReader(SRC), new FileStream(filePath, FileMode.Create),
                                                new StampingProperties());

            pdfSigner.SetCertificationLevel(PdfSigner.CERTIFIED_NO_CHANGES_ALLOWED);

            // Set the name indicating the field to be signed.
            // The field can already be present in the document but shall not be signed
            pdfSigner.SetFieldName("signature");

            ImageData clientSignatureImage = ImageDataFactory.Create(IMAGE_PATH);

            // If you create new signature field (or use SetFieldName(System.String) with
            // the name that doesn't exist in the document or don't specify it at all) then
            // the signature is invisible by default.
            PdfSignatureAppearance signatureAppearance = pdfSigner.GetSignatureAppearance();

            signatureAppearance.SetRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC);
            signatureAppearance.SetReason("");
            signatureAppearance.SetLocationCaption("");
            signatureAppearance.SetSignatureGraphic(clientSignatureImage);
            signatureAppearance.SetPageNumber(signatureInfo.PageNumber);
            signatureAppearance.SetPageRect(new Rectangle(signatureInfo.Left, signatureInfo.Bottom,
                                                          25, 25));

            char[]             password = "******".ToCharArray();
            IExternalSignature pks      = GetPrivateKeySignature(CERT_PATH, password);

            X509Certificate[]      chain        = GetCertificateChain(CERT_PATH, password);
            OCSPVerifier           ocspVerifier = new OCSPVerifier(null, null);
            OcspClientBouncyCastle ocspClient   = new OcspClientBouncyCastle(ocspVerifier);
            List <ICrlClient>      crlClients   = new List <ICrlClient>(new[] { new CrlClientOnline() });

            // Sign the document using the detached mode, CMS or CAdES equivalent.
            // This method closes the underlying pdf document, so the instance
            // of PdfSigner cannot be used after this method call
            pdfSigner.SignDetached(pks, chain, crlClients, ocspClient, null, 0,
                                   PdfSigner.CryptoStandard.CMS);
        }
示例#30
0
        /// <summary>
        /// Method that creates a temporary pdf for calating the hash that must be sent to AMA for signing
        /// </summary>
        /// <param name="signingInformation">Information about the signature and its appearance</param>
        /// <returns>Information with the hashes required for signing and completing the retrieved signature injection</returns>
        public HashesForSigning CreateTemporaryPdfForSigning(SigningInformation signingInformation)
        {
            var pdfSigner = new PdfSigner(new PdfReader(signingInformation.PathToPdf),
                                          new FileStream(signingInformation.PathToIntermediaryPdf, FileMode.Create),
                                          new StampingProperties());

            pdfSigner.SetFieldName(_signatureFieldname);


            var appearance = pdfSigner.GetSignatureAppearance();

            appearance.SetPageRect(new Rectangle(10,
                                                 750,
                                                 150,
                                                 50))
            .SetPageNumber(signingInformation.PageNumber)
            .SetLayer2FontSize(6f)
            .SetReason(signingInformation.Reason)
            .SetLocation(signingInformation.Location)
            .SetLayer2Text(BuildVisibleInformation(signingInformation.Reason, signingInformation.Location))
            .SetCertificate(_userCertificateChain[0]);

            if (signingInformation.Logo != null)
            {
                appearance.SetRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION)
                .SetSignatureGraphic(signingInformation.Logo);
            }


            var crlBytesList = GetCrlByteList();

            var ocspBytesList = GetOcspBytesList();


            var container = new PrefareForAmaSigningContainer(_userCertificateChain, crlBytesList, ocspBytesList);

            pdfSigner.SignExternalContainer(container, EstimateContainerSize(crlBytesList)); // add size for timestamp in signature

            return(new HashesForSigning(container.HashToBeSignedByAma, container.NakedHash));
        }