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);
        }
Exemplo n.º 2
0
        public virtual void LtvEnabledSingleSignatureTest01()
        {
            String signCertFileName         = certsSrc + "signCertRsaWithChain.p12";
            String tsaCertFileName          = certsSrc + "tsCertRsa.p12";
            String intermediateCertFileName = certsSrc + "intermediateRsa.p12";
            String caCertFileName           = certsSrc + "rootRsa.p12";
            String srcFileName = sourceFolder + "helloWorldDoc.pdf";
            String ltvFileName = destinationFolder + "ltvEnabledSingleSignatureTest01.pdf";

            X509Certificate[] tsaChain         = Pkcs12FileHelper.ReadFirstChain(tsaCertFileName, password);
            ICipherParameters tsaPrivateKey    = Pkcs12FileHelper.ReadFirstKey(tsaCertFileName, password, password);
            X509Certificate   intermediateCert = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(intermediateCertFileName
                                                                                                  , password)[0];
            ICipherParameters intermediatePrivateKey = Pkcs12FileHelper.ReadFirstKey(intermediateCertFileName, password
                                                                                     , password);
            X509Certificate   caCert         = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(caCertFileName, password)[0];
            ICipherParameters caPrivateKey   = Pkcs12FileHelper.ReadFirstKey(caCertFileName, password, password);
            TestTsaClient     testTsa        = new TestTsaClient(JavaUtil.ArraysAsList(tsaChain), tsaPrivateKey);
            TestOcspClient    testOcspClient = new TestOcspClient().AddBuilderForCertIssuer(intermediateCert, intermediatePrivateKey
                                                                                            ).AddBuilderForCertIssuer(caCert, caPrivateKey);

            X509Certificate[]  signChain      = Pkcs12FileHelper.ReadFirstChain(signCertFileName, password);
            ICipherParameters  signPrivateKey = Pkcs12FileHelper.ReadFirstKey(signCertFileName, password, password);
            IExternalSignature pks            = new PrivateKeySignature(signPrivateKey, DigestAlgorithms.SHA256);
            PdfSigner          signer         = new PdfSigner(new PdfReader(srcFileName), new FileStream(ltvFileName, FileMode.Create),
                                                              new StampingProperties());

            signer.SetFieldName("Signature1");
            signer.SignDetached(pks, signChain, null, testOcspClient, testTsa, 0, PdfSigner.CryptoStandard.CADES);
            PadesSigTest.BasicCheckSignedDoc(destinationFolder + "ltvEnabledSingleSignatureTest01.pdf", "Signature1");
        }
        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.º 4
0
        public void Sign(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());

            signer.SetFieldName(name);

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

            signer.SignDetached(pks, chain, null, null, null,
                                0, PdfSigner.CryptoStandard.CMS);
        }
        private byte[] Sign(byte[] src, Org.BouncyCastle.X509.X509Certificate[] chain, ICipherParameters pk,
                            string digestAlgorithm, PdfSigner.CryptoStandard subfilter, string signatureFieldName
                            )
        {
            using (MemoryStream outputMemoryStream = new MemoryStream())
                using (MemoryStream memoryStream = new MemoryStream(src))
                    using (PdfReader pdfReader = new PdfReader(memoryStream))
                    {
                        PdfSigner signer = new PdfSigner(
                            pdfReader, outputMemoryStream,
                            new StampingProperties().UseAppendMode()
                            );

                        signer.SetFieldName(signatureFieldName);

                        IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm);

                        try
                        {
                            // Sign the document using the detached mode, CMS or CAdES equivalent.
                            signer.SignDetached(pks, chain, null, null, null, 0, subfilter);
                        }
                        catch (Exception ex)
                        {
                            throw;
                        }

                        pdfReader.Close();
                        memoryStream.Close();
                        var documentoAssinado = outputMemoryStream.ToArray();
                        outputMemoryStream.Close();

                        return(documentoAssinado);
                    }
        }
Exemplo n.º 6
0
        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.
            signer.SignDetached(pks, chain, crlList, ocspClient, tsaClient, estimatedSize, subfilter);
        }
Exemplo n.º 7
0
        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);
            }
        }
Exemplo n.º 8
0
        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), true);
            // 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);
        }
Exemplo n.º 9
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);
        }
        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);
        }
Exemplo n.º 11
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)
            {
            }
        }
Exemplo n.º 12
0
        public void Sign(String src, String dest, X509Certificate[] chain, 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
            //Rectangle rect = new Rectangle(36, 648, 200, 100);
            //iText.Signatures.PdfSignatureAppearance appearance = signer.GetSignatureAppearance();
            //appearance
            //    .SetReason(reason)
            //    .SetLocation(location)
            //    .SetPageRect(rect)
            //    .SetPageNumber(1);
            signer.SetFieldName("QAMgr");


            //IExternalDigest digest = new BouncyCastleDigest();
            IExternalSignature signature = new ServerSignature();

            //IExternalSignature sing = new

            // Sign the document using the detached mode, CMS or CAdES equivalent.
            //signer.SignDetached(digest, signature, chain, null, null, null,
            //        0, subfilter);

            // Sign the document using the detached mode, CMS or CAdES equivalent.
            signer.SignDetached(signature, chain, null, null, null, 0, subfilter);
        }
Exemplo n.º 13
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);
        }
Exemplo n.º 14
0
        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);
            PdfFont font = PdfFontFactory.CreateFont(FONT, "WinAnsi", true);
            // Creating the appearance
            PdfSignatureAppearance appearance = signer.GetSignatureAppearance().SetReason(reason).SetLocation(location
                                                                                                              ).SetLayer2Font(font).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);
        }
Exemplo n.º 15
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);
            });
        }
        /// <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);
        }
Exemplo n.º 17
0
        protected internal virtual void Sign(String src, String name, String dest, X509Certificate[] chain, ICipherParameters
                                             pk, String digestAlgorithm, PdfSigner.CryptoStandard subfilter, int certificationLevel)
        {
            PdfReader          reader     = new PdfReader(src);
            StampingProperties properties = new StampingProperties();

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

            signer.SetCertificationLevel(certificationLevel);
            signer.SetFieldName(name);
            // Creating the signature
            IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm);

            signer.SignDetached(pks, chain, null, null, null, 0, subfilter);
        }
Exemplo n.º 18
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);
        }
Exemplo n.º 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));
        }
        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);
        }
Exemplo n.º 21
0
        /// <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);
                }
        }
Exemplo n.º 22
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);
        }
        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);
        }
Exemplo n.º 24
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");
        }
Exemplo n.º 25
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_"));
        }
Exemplo n.º 26
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.º 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);
        }
Exemplo n.º 28
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);
        }
Exemplo n.º 29
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.º 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));
        }