Esempio n. 1
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);
            // Creating the appearance
            PdfSignatureAppearance appearance = signer.GetSignatureAppearance().SetReason(reason).SetLocation(location
                                                                                                              ).SetReuseAppearance(setReuseAppearance);

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

            signer.SignDetached(pks, chain, null, null, null, 0, subfilter);
        }
Esempio n. 2
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();
        }
Esempio n. 3
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;
        }
Esempio n. 4
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);
        }
Esempio n. 5
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);
        }
Esempio n. 6
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);
        }
Esempio n. 7
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;
        }
Esempio n. 8
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);
        }
Esempio n. 9
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));
                }
            }
        }
Esempio n. 10
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());
                }
            }
        }
Esempio n. 11
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);
        }
Esempio n. 12
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);
        }
Esempio n. 13
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();
        }