Exemplo n.º 1
0
        public virtual void FormFillingAppend_form_filled_Test()
        {
            String             srcFilename = sourceFolder + "Form_Empty.pdf";
            String             temp        = destinationFolder + "temp_filled.pdf";
            String             filename    = destinationFolder + "formFillingAppend_form_filled.pdf";
            StampingProperties props       = new StampingProperties();

            props.UseAppendMode();
            PdfDocument doc  = new PdfDocument(new PdfReader(srcFilename), new PdfWriter(temp), props);
            PdfAcroForm form = PdfAcroForm.GetAcroForm(doc, true);

            foreach (PdfFormField field in form.GetFormFields().Values)
            {
                field.SetValue("Different");
            }
            doc.Close();
            Flatten(temp, filename);
            new FileInfo(temp).Delete();
            CompareTool compareTool  = new CompareTool();
            String      errorMessage = compareTool.CompareByContent(filename, sourceFolder + "cmp_formFillingAppend_form_filled.pdf"
                                                                    , destinationFolder, "diff_");

            if (errorMessage != null)
            {
                NUnit.Framework.Assert.Fail(errorMessage);
            }
        }
Exemplo n.º 2
0
        /// <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);
            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.º 3
0
        public PdfADocument(PdfReader reader, PdfWriter writer, StampingProperties properties)
            : base(reader, writer, properties)
        {
            byte[] existingXmpMetadata = GetXmpMetadata();
            if (existingXmpMetadata == null)
            {
                throw new PdfAConformanceException(PdfAConformanceException.DocumentToReadFromShallBeAPdfAConformantFileWithValidXmpMetadata
                                                   );
            }
            XMPMeta meta;

            try {
                meta = XMPMetaFactory.ParseFromBuffer(existingXmpMetadata);
            }
            catch (XMPException) {
                throw new PdfAConformanceException(PdfAConformanceException.DocumentToReadFromShallBeAPdfAConformantFileWithValidXmpMetadata
                                                   );
            }
            PdfAConformanceLevel conformanceLevel = PdfAConformanceLevel.GetConformanceLevel(meta);

            if (conformanceLevel == null)
            {
                throw new PdfAConformanceException(PdfAConformanceException.DocumentToReadFromShallBeAPdfAConformantFileWithValidXmpMetadata
                                                   );
            }
            SetChecker(conformanceLevel);
        }
Exemplo n.º 4
0
        /// <summary>Open a PDF/A document in stamping mode.</summary>
        /// <param name="reader">PDF reader.</param>
        /// <param name="writer">PDF writer.</param>
        /// <param name="properties">properties of the stamping process</param>
        public PdfADocument(PdfReader reader, PdfWriter writer, StampingProperties properties)
            : base(reader, writer, properties)
        {
            byte[] existingXmpMetadata = GetXmpMetadata();
            if (existingXmpMetadata == null)
            {
                throw new PdfAConformanceException(PdfAConformanceException.DOCUMENT_TO_READ_FROM_SHALL_BE_A_PDFA_CONFORMANT_FILE_WITH_VALID_XMP_METADATA
                                                   );
            }
            XMPMeta meta;

            try {
                meta = XMPMetaFactory.ParseFromBuffer(existingXmpMetadata);
            }
            catch (XMPException) {
                throw new PdfAConformanceException(PdfAConformanceException.DOCUMENT_TO_READ_FROM_SHALL_BE_A_PDFA_CONFORMANT_FILE_WITH_VALID_XMP_METADATA
                                                   );
            }
            PdfAConformanceLevel conformanceLevel = PdfAConformanceLevel.GetConformanceLevel(meta);

            if (conformanceLevel == null)
            {
                throw new PdfAConformanceException(PdfAConformanceException.DOCUMENT_TO_READ_FROM_SHALL_BE_A_PDFA_CONFORMANT_FILE_WITH_VALID_XMP_METADATA
                                                   );
            }
            SetChecker(conformanceLevel);
        }
Exemplo n.º 5
0
        public static void AssinaComCertificado(List <ICrlClient> crlList, string FileName, string SignFileName, CertSimples cert, int X, int Y, int Pagina, int Rotation, bool AddTimeStamper = true, string urlTimeStamper = "https://freetsa.org/tsr", string timeStampUser = "", string timeStampPass = "", string Reason = "Assinatura Digital", bool AplicaPolitica = false, string MyDigestAlgorithm = "SHA-256", string Contact = "", string Location = "Indústrias Nucleares do Brasil S/A - INB", string Creator = "Assinador da INB", TipoAssinatura Tipo = TipoAssinatura.Normal, string Cargo = "", string CREACRM = "")
        {
            string             SourcePdfFileName = FileName;
            string             DestPdfFileName   = SignFileName;
            int                Largura           = 140;
            int                Altura            = 63;
            PdfReader          pdfReader         = new PdfReader(SourcePdfFileName);
            FileStream         signedPdf         = new FileStream(DestPdfFileName, FileMode.Create, FileAccess.ReadWrite);
            StampingProperties osp = new StampingProperties();

            osp.UseAppendMode();
            PdfSigner   objStamper = new PdfSigner(pdfReader, signedPdf, osp);
            ITSAClient  tsaClient  = null;
            IOcspClient ocspClient = null;

            ConfiguraAparencia(objStamper, cert, X, Y, Largura, Altura, Pagina, Rotation, Contact, Reason, Location, Creator, Tipo);

            Org.BouncyCastle.X509.X509Certificate       vert       = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(cert.Certificado);
            Org.BouncyCastle.X509.X509CertificateParser cp         = new Org.BouncyCastle.X509.X509CertificateParser();
            Org.BouncyCastle.X509.X509Certificate[]     Arraychain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(cert.Certificado.RawData) };
            X509CertificateParser objCP = new X509CertificateParser();

            RSACryptoServiceProvider rsa;
            RSACryptoServiceProvider Provider;
            IExternalSignature       externalSignature;

            if (cert.Certificado.PrivateKey is RSACryptoServiceProvider)
            {
                rsa               = (RSACryptoServiceProvider)cert.Certificado.PrivateKey;
                Provider          = (RSACryptoServiceProvider)cert.Certificado.PrivateKey;
                externalSignature = new AsymmetricAlgorithmSignature(Provider, MyDigestAlgorithm);
            }
            else
            {
                //RETIRAR ESSA PARTE PARA IMPLEMENTAR OS DEMAIS MÉTODOS, OLHANDO OUTROS TIPOS DE CERTIFICADO
                rsa               = (RSACryptoServiceProvider)cert.Certificado.PrivateKey;
                Provider          = (RSACryptoServiceProvider)cert.Certificado.PrivateKey;
                externalSignature = new AsymmetricAlgorithmSignature(Provider, MyDigestAlgorithm);
            }
            if (AddTimeStamper)
            {
                tsaClient = new TSAClientBouncyCastle(urlTimeStamper, timeStampUser, timeStampPass);
            }
            OCSPVerifier ocspVerifier = new OCSPVerifier(null, null);

            ocspClient = new OcspClientBouncyCastle(ocspVerifier);
            if (AplicaPolitica)
            {
                SignaturePolicyInfo spi = getPolitica();
                objStamper.SignDetached(externalSignature, Arraychain, crlList, ocspClient, tsaClient, 0, PdfSigner.CryptoStandard.CADES, spi);
            }
            else
            {
                objStamper.SignDetached(externalSignature, Arraychain, crlList, ocspClient, tsaClient, 0, PdfSigner.CryptoStandard.CADES);
            }
            try { signedPdf.Flush(); }
            catch { }
            try { signedPdf.Close(); } catch { };
            pdfReader.Close();
        }
Exemplo n.º 6
0
        /// <summary>Creates a PdfSigner instance.</summary>
        /// <remarks>
        /// Creates a PdfSigner instance. Uses a
        /// <see cref="System.IO.MemoryStream"/>
        /// instead of a temporary file.
        /// </remarks>
        /// <param name="reader">PdfReader that reads the PDF file</param>
        /// <param name="outputStream">OutputStream to write the signed PDF file</param>
        /// <param name="path">File to which the output is temporarily written</param>
        /// <param name="append">boolean to indicate whether the signing should happen in append mode or not</param>
        /// <exception cref="System.IO.IOException"/>
        public PdfSigner(PdfReader reader, Stream outputStream, String path, bool append)
        {
            StampingProperties properties = new StampingProperties().PreserveEncryption();

            if (append)
            {
                properties.UseAppendMode();
            }
            if (path == null)
            {
                temporaryOS = new MemoryStream();
                document    = new PdfDocument(reader, new PdfWriter(temporaryOS), properties);
            }
            else
            {
                this.tempFile = FileUtil.CreateTempFile(path);
                document      = new PdfDocument(reader, new PdfWriter(FileUtil.GetFileOutputStream(tempFile)), properties);
            }
            originalOS = outputStream;
            signDate   = DateTimeUtil.GetCurrentTime();
            fieldName  = GetNewSigFieldName();
            appearance = new PdfSignatureAppearance(document, new Rectangle(0, 0), 1);
            appearance.SetSignDate(signDate);
            closed = false;
        }
Exemplo n.º 7
0
        private void AdicionarLtv(string pdfPrimeiraAssinatura, SingInfo singInfo)
        {
            var inicioCarimbo = DateTime.Now;

            var stamping = new StampingProperties();

            stamping.UseAppendMode();

            PdfDocument pdfDoc = new PdfDocument(
                new PdfReader(pdfPrimeiraAssinatura),
                new PdfWriter(singInfo.TargetPdf));

            LtvVerification v             = new LtvVerification(pdfDoc);
            SignatureUtil   signatureUtil = new SignatureUtil(pdfDoc);

            var names   = signatureUtil.GetSignatureNames();
            var sigName = names[names.Count - 1];

            var pkcs7 = signatureUtil.VerifySignature(sigName);

            if (pkcs7.IsTsp())
            {
                v.AddVerification(
                    sigName,
                    this.ocspClient,
                    new CrlClientOnline(this.cadeiaTempo.ToArray()),
                    LtvVerification.CertificateOption.SIGNING_CERTIFICATE,
                    LtvVerification.Level.OCSP_CRL,
                    LtvVerification.CertificateInclusion.YES);
            }
            else
            {
                foreach (var name in names)
                {
                    v.AddVerification(
                        name,
                        this.ocspClient,
                        new CrlClientOnline(this.cadeiaTempo.ToArray()),
                        LtvVerification.CertificateOption.WHOLE_CHAIN,
                        LtvVerification.Level.OCSP_CRL,
                        LtvVerification.CertificateInclusion.NO);
                }
            }

            pdfDoc.Close();

            Console.WriteLine("Aplicando timestamp........");
            PdfReader r         = new PdfReader(pdfPrimeiraAssinatura);
            PdfSigner pdfSigner = new PdfSigner(r, new FileStream(singInfo.TargetPdf, FileMode.Create), stamping);

            pdfSigner.Timestamp(this.tsaClient, null);

            var fimCarimbo = DateTime.Now;

            var tempoCarimbo = fimCarimbo.Subtract(inicioCarimbo);

            Console.WriteLine("Tempo Carimbo: {0}ms", tempoCarimbo.TotalMilliseconds);
        }
Exemplo n.º 8
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);
        }
Exemplo n.º 9
0
 protected override PdfDocument InitDocument(PdfReader reader, PdfWriter writer, StampingProperties properties)
 {
     try
     {
         return(base.InitDocument(reader, writer, properties));
     }
     finally
     {
         FieldInfo        propertiesField  = typeof(PdfWriter).GetField("properties", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
         WriterProperties writerProperties = (WriterProperties)propertiesField.GetValue(writer);
         writerProperties.SetFullCompressionMode(false);
     }
 }
Exemplo n.º 10
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());
                        }
                    }
        }
Exemplo n.º 11
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.º 12
0
        public override async Task SignPdf(string fileId, byte[] fileData)
        {
            SignedFileEventArgs eventArgs = null;

            if (String.IsNullOrWhiteSpace(pin) || privatekeyHandle == null)
            {
                eventArgs = new SignedFileEventArgs(null, fileId, true, "El pin es requerido.\nO bien no fue ingresado, o era incorrecto.");
            }

            else
            {
                using (var memStream = new MemoryStream(fileData))
                    using (PdfReader reader = new PdfReader(memStream))
                    {
                        StampingProperties properties = new StampingProperties();
                        properties.UseAppendMode();

                        using (MemoryStream outputStream = new MemoryStream())
                        {
                            try
                            {
                                PdfSigner signer = new PdfSigner(reader, outputStream, properties);

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

                                signer.SignDetached(externalSignature, certPath, null, null, null, 0, PdfSigner.CryptoStandard.CADES);
                                eventArgs = new SignedFileEventArgs(outputStream.ToArray(), fileId, false, "");
                            }
                            catch (Exception e)
                            {
                                logger.Error(e, "Error firmando archivo {fileId}\n{mensaje}", fileId, e.Message);
                                eventArgs = new SignedFileEventArgs(null, fileId, true, e.Message);
                            }
                        }
                    }
            }
            OnRaiseSignedFileEvent(eventArgs);
            await Task.CompletedTask;
        }
Exemplo n.º 13
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);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Methods which returns base64 digested PDF.
        /// </summary>
        /// <param name="unsignedPdf">Path to pdf which needs to be signed</param>
        /// <param name="tempPdf">Path to temporary pdf</param>
        /// <param name="signatureFieldName">Name of field</param>
        /// <returns></returns>
        public static string GetBytesToSign(string unsignedPdf, string tempPdf, string signatureFieldName)
        {
            if (File.Exists(tempPdf))
            {
                File.Delete(tempPdf);
            }

            using (PdfReader reader = new PdfReader(unsignedPdf))
            {
                using (FileStream os = File.OpenWrite(tempPdf))
                {
                    StampingProperties sp = new StampingProperties();
                    sp.UseAppendMode();

                    PdfSigner pdfSigner = new PdfSigner(reader, os, sp);
                    pdfSigner.SetFieldName(signatureFieldName);

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

                    //Creating container for emty signature, with atrivute where digest is calculated.
                    //ExternalHashingSignatureContainer external = new ExternalHashingSignatureContainer(PdfName.Adobe_PPKLite, PdfName.Adbe_pkcs7_detached);
                    //pdfSigner.SignExternalContainer(external, 8192);
                    //hash = external.Hash;

                    //Creating container for empty signature.
                    IExternalSignatureContainer external = new ExternalBlankSignatureContainer(PdfName.Adobe_PPKLite, PdfName.Adbe_x509_rsa_sha1);
                    pdfSigner.SignExternalContainer(external, 8192);

                    //Digest from created new temporary PDF with empty space for signature.
                    FileStream oso = File.OpenRead(temp);
                    hash = DigestAlgorithms.Digest(oso, DigestAlgorithms.SHA256);

                    return(Convert.ToBase64String(hash));
                }
            }
        }
Exemplo n.º 15
0
        public static void signPdfFile(string sourceDocument, string destinationPath, Stream privateKeyStream, string keyPassword, string reason, string location)
        {
            Pkcs12Store pk12 = new Pkcs12Store(privateKeyStream, keyPassword.ToCharArray());

            privateKeyStream.Dispose();

            //then Iterate throught certificate entries to find the private key entry
            string alias = null;

            foreach (string tAlias in pk12.Aliases)
            {
                if (pk12.IsKeyEntry(tAlias))
                {
                    alias = tAlias;
                    break;
                }
            }
            var pk    = pk12.GetKey(alias).Key;
            var ce    = pk12.GetCertificateChain(alias);
            var chain = new X509Certificate[ce.Length];

            for (int k = 0; k < ce.Length; ++k)
            {
                chain[k] = ce[k].Certificate;
            }
            // reader and stamper
            PdfReader          reader     = new PdfReader(sourceDocument);
            FileStream         fout       = new FileStream(destinationPath, FileMode.Create, FileAccess.ReadWrite);
            StampingProperties properties = new StampingProperties();
            PdfSigner          signer     = new PdfSigner(reader, fout, properties);

            PdfSignatureAppearance appearance = signer.GetSignatureAppearance().SetReason(reason).SetLocation(location);
            IExternalSignature     pks        = new PrivateKeySignature(pk, "SHA-512");

            signer.SignDetached(pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CMS);
        }
Exemplo n.º 16
0
        public static void AssinaComCertificado(List <ICrlClient> crlList, byte[] File, out byte[] SignFile, CertSimples cert, int X, int Y, int Pagina, int Rotation, bool AddTimeStamper = true, string urlTimeStamper = "https://freetsa.org/tsr", string timeStampUser = "", string timeStampPass = "", string Reason = "Assinatura Digital", bool AplicaPolitica = false, string MyDigestAlgorithm = "SHA-256", string Contact = "", string Location = "Indústrias Nucleares do Brasil S/A - INB", string Creator = "Assinador da INB", TipoAssinatura Tipo = TipoAssinatura.Normal, string Cargo = "", string CREACRM = "")
        {
            int                Largura       = 140;
            int                Altura        = 63;
            MemoryStream       ArquivoOrigem = new MemoryStream(File);
            PdfReader          pdfReader     = new PdfReader(ArquivoOrigem);
            MemoryStream       signedPdf     = new MemoryStream();
            StampingProperties osp           = new StampingProperties();

            osp.UseAppendMode();
            PdfSigner   objStamper = new PdfSigner(pdfReader, signedPdf, osp);
            ITSAClient  tsaClient  = null;
            IOcspClient ocspClient = null;

            ConfiguraAparencia(objStamper, cert, X, Y, Largura, Altura, Pagina, Rotation, Contact, Reason, Location, Creator, Tipo, Cargo, CREACRM);

            Org.BouncyCastle.X509.X509Certificate       vert       = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(cert.Certificado);
            Org.BouncyCastle.X509.X509CertificateParser cp         = new Org.BouncyCastle.X509.X509CertificateParser();
            Org.BouncyCastle.X509.X509Certificate[]     Arraychain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(cert.Certificado.RawData) };
            X509CertificateParser objCP = new X509CertificateParser();

            RSACryptoServiceProvider rsa;
            RSACryptoServiceProvider Provider;
            IExternalSignature       externalSignature;

            if (cert.Certificado.PrivateKey is RSACryptoServiceProvider)
            {
                rsa               = (RSACryptoServiceProvider)cert.Certificado.PrivateKey;
                Provider          = (RSACryptoServiceProvider)cert.Certificado.PrivateKey;
                externalSignature = new AsymmetricAlgorithmSignature(Provider, MyDigestAlgorithm);
            }
            else
            {
                RSA rsaTeste = cert.Certificado.GetRSAPrivateKey();

                rsa               = (RSACryptoServiceProvider)cert.Certificado.PrivateKey;
                Provider          = (RSACryptoServiceProvider)cert.Certificado.PrivateKey;
                externalSignature = new AsymmetricAlgorithmSignature(Provider, MyDigestAlgorithm);
            }

            if (AddTimeStamper)
            {
                tsaClient = new TSAClientBouncyCastle(urlTimeStamper, timeStampUser, timeStampPass);
            }
            OCSPVerifier ocspVerifier = new OCSPVerifier(null, null);

            ocspClient = new OcspClientBouncyCastle(ocspVerifier);
            if (AplicaPolitica)
            {
                SignaturePolicyInfo spi = getPolitica();
                objStamper.SignDetached(externalSignature, Arraychain, crlList, ocspClient, tsaClient, 0, PdfSigner.CryptoStandard.CADES, spi);
            }
            else
            {
                objStamper.SignDetached(externalSignature, Arraychain, crlList, ocspClient, tsaClient, 0, PdfSigner.CryptoStandard.CADES);
            }

            try
            {
                SignFile = signedPdf.ToArray();
                try
                {
                    signedPdf.Close();
                    signedPdf.Dispose();
                }
                catch { }
            }
            catch (Exception ex)
            {
                SignFile = null;
                throw ex;
            }
            try
            {
                signedPdf.Close();
            }
            catch (Exception ex) { }
            pdfReader.Close();
        }
Exemplo n.º 17
0
        public static byte[] Sign(IExternalSignature externalSignature, X509Certificate[] certChain, string src, string friendlyName, string subject, string sourceName, string documentLink, string documentName)
        {
            int numberOfSignatures = 0;
            int numberOfPages      = 0;

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

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

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

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

            float posSignY = 615 - (numberOfSignatures * 70);

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

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

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

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

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

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

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

                    return(ms.ToArray());
                }
            }
        }
Exemplo n.º 18
0
        static int Main(string[] args)
        {
            if (args.Length == 0)
            {
                PrintUsage();
                return((int)ExitCode.Success);
            }

            Arguments.Populate();

            if (string.IsNullOrEmpty(SourceFile))
            {
                PrintUsage();
                return((int)ExitCode.NoInputFile);
            }

            if (string.IsNullOrEmpty(DestinationFile))
            {
                PrintUsage();
                return((int)ExitCode.NoOutputFile);
            }

            if (string.IsNullOrEmpty(Pincode))
            {
                PrintUsage();
                return((int)ExitCode.NoPin);
            }

            using (EidSignature eidSignature = new EidSignature(Pincode))
            {
                if (eidSignature.ReadersCount == 0)
                {
                    Console.WriteLine("No card reader connected");
                    return((int)ExitCode.NoCardReader);
                }

                if (eidSignature.IsCardInserted == false)
                {
                    Console.WriteLine("No eid card inserted in the reader");
                    return((int)ExitCode.NoCardInserted);
                }

                // When signing certificate is stored on the token it can be usually read with GetSigningCertificate() method
                byte[] signingCertificate = eidSignature.GetSigningCertificate();
                if (signingCertificate == null)
                {
                    Console.WriteLine("No signing certificate found");
                    return((int)ExitCode.NoCertificate);
                }


                // All certificates stored on the token can be usually read with GetAllCertificates() method
                List <byte[]> otherCertificates = eidSignature.GetAllCertificates();

                // Build certification path for the signing certificate
                ICollection <Org.BouncyCastle.X509.X509Certificate> certPath = eidSignature.BuildCertPath(signingCertificate, otherCertificates);
                Org.BouncyCastle.X509.X509Certificate   bcCert = new X509CertificateParser().ReadCertificate(signingCertificate);
                Org.BouncyCastle.X509.X509Certificate[] chain  = new Org.BouncyCastle.X509.X509Certificate[1] {
                    bcCert
                };
                //ICipherParameters pk = signatureCert.GetECDsaPrivateKey();

                TSAClientBouncyCastle tsaClient = new TSAClientBouncyCastle("http://tsa.belgium.be/connect");

                // Read unsigned PDF document
                using (PdfReader pdfReader = new PdfReader(SourceFile))
                {
                    using (FileStream outputStream = new FileStream(DestinationFile, FileMode.Create))
                    {
                        // Create PdfStamper that applies extra content to the PDF document

                        StampingProperties properties = new StampingProperties();
                        properties.UseAppendMode();

                        PdfSigner signer = new PdfSigner(pdfReader, outputStream, properties);
                        {
                            PdfSignatureAppearance appearance = signer.GetSignatureAppearance();

                            List <ICrlClient> crlList = new List <ICrlClient>();
                            crlList.Add(new CrlClientOnline("http://crl.eid.belgium.be/belgium2.crl"));
                            crlList.Add(new CrlClientOnline("http://crl.eid.belgium.be/belgium3.crl"));
                            crlList.Add(new CrlClientOnline("http://crl.eid.belgium.be/belgium4.crl"));

                            // Sign PDF document
                            try
                            {
                                signer.SignDetached(eidSignature, chain, crlList, null, tsaClient, 0, PdfSigner.CryptoStandard.CADES);
                            }
                            catch (NullReferenceException e)
                            {
                                Console.WriteLine("Can't read the certificate from the card");
                                return((int)ExitCode.NoCertificate);
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e.Message);
                                return((int)ExitCode.UnknownError);
                            }
                        }
                    }
                }
            }

            return((int)ExitCode.Success);
        }
Exemplo n.º 19
0
        public string Execute(SingInfo singInfo)
        {
            var inicioCertificado = DateTime.Now;

            var certificate = this.certificadoA3.Obter();

            this.cadeiaTempo = this.certificadoA3.CadeiaCertificadoTempo();

            this.MontarEstruturaCertificacao(certificate);

            var fimCertificado = DateTime.Now;

            var pdfAux = Path.Combine(
                Path.GetDirectoryName(singInfo.SourcePdf),
                Path.GetFileNameWithoutExtension(singInfo.SourcePdf) + "-aux.pdf");

            var inicioAssinatura = DateTime.Now;

            using (var reader = new PdfReader(singInfo.SourcePdf))
            {
                var stamping = new StampingProperties();

                stamping.UseAppendMode();

                var pdfSigner = new PdfSigner(reader, new FileStream(pdfAux, FileMode.Create), stamping);

                var caminhoFonte2 = @"C:\Windows\Fonts\cour.ttf";

                PdfSignatureAppearance appearance = pdfSigner
                                                    .GetSignatureAppearance()
                                                    .SetReason(singInfo.SignatureReason)
                                                    .SetLocation(singInfo.SignatureLocation)
                                                    .SetReuseAppearance(false)
                                                    .SetContact(singInfo.SignatureContact)
                                                    .SetLayer2Font(PdfFontFactory.CreateFont(caminhoFonte2, iText.IO.Font.PdfEncodings.WINANSI, true));

                appearance.SetRenderingMode(PdfSignatureAppearance.RenderingMode.DESCRIPTION);

                var pks = new X509Certificate2Signature(certificate, DigestAlgorithms.SHA256);

                Console.WriteLine("assinando...");

                pdfSigner.SignDetached(
                    pks,
                    this.chain.ToArray(),
                    this.crlList,
                    this.ocspClient,
                    this.tsaClient,
                    EstimatedSize,
                    CryptoStandard.CMS);
            }

            var fimAssinatura = DateTime.Now;

            var tempoAssinatura  = fimAssinatura.Subtract(inicioAssinatura);
            var tempoCertificado = fimCertificado.Subtract(inicioCertificado);

            Console.WriteLine("Tempo Assinatura: {0}ms", tempoAssinatura.TotalMilliseconds);
            Console.WriteLine("Tempo Certificado: {0}ms", tempoCertificado.TotalMilliseconds);

            this.AdicionarLtv(pdfAux, singInfo);

            this.RemoverArquivoTemporario(pdfAux);

            return(singInfo.TargetPdf);
        }
Exemplo n.º 20
0
 public PdfSignerNoObjectStream(PdfReader reader, Stream outputStream, StampingProperties properties) : base(reader, outputStream, properties)
 {
 }
Exemplo n.º 21
0
        public byte[] GenerirajPotpisaniDokument(byte[] document, string documentName, string signingReason, string signingLocation)
        {
            try
            {
                string alias = "";
                List <Org.BouncyCastle.X509.X509Certificate> chain = new List <Org.BouncyCastle.X509.X509Certificate>();

                var location = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AppDomain.CurrentDomain.RelativeSearchPath ?? "");
                //var destinationPath = $@"Data\{documentName}";
                //destinationPath = Path.Combine(location, destinationPath);
                var destinationPath = iConfig["DocumentDestinationPath"] + documentName;


                var certPath = @"C:\Users\Crega\Source\Repos\PdfSigner\PdfSigner\bin\Debug\netcoreapp3.0\certifikat.pfx";
                certPath = Path.Combine(location, certPath);
                var    cert       = File.ReadAllBytes(certPath);
                Stream certStream = new MemoryStream(cert);

                Pkcs12Store store = new Pkcs12Store(certStream, "12345".ToCharArray());

                // searching for private key
                foreach (string al in store.Aliases)
                {
                    if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate)
                    {
                        alias = al;
                        break;
                    }
                }
                AsymmetricKeyEntry pk = store.GetKey(alias);
                foreach (X509CertificateEntry c in store.GetCertificateChain(alias))
                {
                    chain.Add(c.Certificate);
                }
                RsaPrivateCrtKeyParameters parameters = pk.Key as RsaPrivateCrtKeyParameters;

                Stream                     documentStream = new MemoryStream(document);
                PdfReader                  reader         = new PdfReader(documentStream);
                FileStream                 os             = new FileStream(destinationPath, FileMode.Create);
                StampingProperties         sp             = new StampingProperties();
                iText.Signatures.PdfSigner signer         = new iText.Signatures.PdfSigner(reader, os, sp);
                PdfSignatureAppearance     appearance     = signer.GetSignatureAppearance();
                appearance.SetReason(signingReason);
                appearance.SetLocation(signingLocation);
                appearance.SetContact("*****@*****.**");
                //appearance.SetPageRect(new iText.Kernel.Geom.Rectangle(36, 748, 144, 780));
                appearance.SetPageNumber(1);
                appearance.SetCertificate(chain[0]);

                // Creating the signature
                IExternalSignature pks = new PrivateKeySignature(parameters, DigestAlgorithms.SHA256);
                signer.SignDetached(pks, chain.ToArray(), null, null, null, 0, iText.Signatures.PdfSigner.CryptoStandard.CADES);
                //MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES);
                os.Close();
                certStream.Close();
                var documentToReturn = File.ReadAllBytes(destinationPath);
                File.Delete(destinationPath);
                return(documentToReturn);
            }
            catch (Exception ex)
            {
            }
            return(null);
        }