public static void addLTV(String src, String dest, IOcspClient ocsp, ICrlClient crl, ITSAClient itsaClient)
        {
            PdfReader       reader        = new PdfReader(src);
            PdfWriter       writer        = new PdfWriter(dest);
            PdfDocument     pdfDoc        = new PdfDocument(reader, writer, new StampingProperties().UseAppendMode());
            LtvVerification v             = new LtvVerification(pdfDoc);
            SignatureUtil   signatureUtil = new SignatureUtil(pdfDoc);
            IList <string>  names         = signatureUtil.GetSignatureNames();
            String          sigName       = names[names.Count - 1];
            PdfPKCS7        pkcs7         = signatureUtil.ReadSignatureData(sigName);

            if (pkcs7.IsTsp())
            {
                v.AddVerification(sigName, ocsp, crl, LtvVerification.CertificateOption.WHOLE_CHAIN,
                                  LtvVerification.Level.OCSP_CRL, LtvVerification.CertificateInclusion.NO);
            }
            else
            {
                foreach (var name in names)
                {
                    v.AddVerification(name, ocsp, crl, LtvVerification.CertificateOption.WHOLE_CHAIN,
                                      LtvVerification.Level.OCSP_CRL, LtvVerification.CertificateInclusion.NO);
                }
            }
            v.Merge();
            pdfDoc.Close();
        }
Example #2
0
        public void AddLtv(String src, String dest, IOcspClient ocsp, ICrlClient crl, ITSAClient tsa)
        {
            PdfReader       r       = new PdfReader(src);
            FileStream      fos     = new FileStream(dest, FileMode.Create);
            PdfStamper      stp     = PdfStamper.CreateSignature(r, fos, '\0', null, true);
            LtvVerification v       = stp.LtvVerification;
            AcroFields      fields  = stp.AcroFields;
            List <String>   names   = fields.GetSignatureNames();
            String          sigName = names[names.Count - 1];
            PdfPKCS7        pkcs7   = fields.VerifySignature(sigName);

            if (pkcs7.IsTsp)
            {
                v.AddVerification(sigName, ocsp, crl, LtvVerification.CertificateOption.SIGNING_CERTIFICATE, LtvVerification.Level.OCSP_CRL, LtvVerification.CertificateInclusion.NO);
            }
            else
            {
                foreach (String name in names)
                {
                    v.AddVerification(name, ocsp, crl, LtvVerification.CertificateOption.WHOLE_CHAIN, LtvVerification.Level.OCSP_CRL, LtvVerification.CertificateInclusion.NO);
                }
            }
            PdfSignatureAppearance sap = stp.SignatureAppearance;

            LtvTimestamp.Timestamp(sap, tsa, null);
        }
Example #3
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();
        }
Example #4
0
 public void Sign(String src, String dest,
                  ICollection<X509Certificate> chain, X509Certificate2 pk,
                  String digestAlgorithm, CryptoStandard subfilter,
                  String reason, String location,
                  ICollection<ICrlClient> crlList,
                  IOcspClient ocspClient,
                  ITSAClient tsaClient,
                  int estimatedSize) {
     // Creating the reader and the stamper
     PdfReader reader = null;
     PdfStamper stamper = null;
     FileStream os = null;
     try {
         reader = new PdfReader(src);
         os = new FileStream(dest, FileMode.Create);
         stamper = PdfStamper.CreateSignature(reader, os, '\0');
         // Creating the appearance
         PdfSignatureAppearance appearance = stamper.SignatureAppearance;
         appearance.Reason = reason;
         appearance.Location = location;
         appearance.SetVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig");
         // Creating the signature
         IExternalSignature pks = new X509Certificate2Signature(pk, digestAlgorithm);
         MakeSignature.SignDetached(appearance, pks, chain, crlList, ocspClient, tsaClient, estimatedSize,
                                    subfilter);
     }
     finally {
         if (reader != null)
             reader.Close();
         if (stamper != null)
             stamper.Close();
         if (os != null)
             os.Close();
     }
 }
        /**
         * Signs the document using the detached mode, CMS or CAdES equivalent.
         * @param sap the PdfSignatureAppearance
         * @param externalSignature the interface providing the actual signing
         * @param chain the certificate chain
         * @param crlList the CRL list
         * @param ocspClient the OCSP client
         * @param tsaClient the Timestamp client
         * @param provider the provider or null
         * @param estimatedSize the reserved size for the signature. It will be estimated if 0
         * @param cades true to sign CAdES equivalent PAdES-BES, false to sign CMS
         * @throws DocumentException 
         * @throws IOException 
         * @throws GeneralSecurityException 
         * @throws NoSuchAlgorithmException 
         * @throws Exception 
         */
        public static void SignDetached(PdfSignatureAppearance sap, IExternalSignature externalSignature, ICollection<X509Certificate> chain, ICollection<ICrlClient> crlList, IOcspClient ocspClient,
                ITSAClient tsaClient, int estimatedSize, CryptoStandard sigtype) {
            List<X509Certificate> certa = new List<X509Certificate>(chain);
            ICollection<byte[]> crlBytes = null;
            int i = 0;
            while (crlBytes == null && i < certa.Count)
        	    crlBytes = ProcessCrl(certa[i++], crlList);
            if (estimatedSize == 0) {
                estimatedSize = 8192;
                if (crlBytes != null) {
                    foreach (byte[] element in crlBytes) {
                        estimatedSize += element.Length + 10;
                    }
                }
                if (ocspClient != null)
                    estimatedSize += 4192;
                if (tsaClient != null)
                    estimatedSize += 4192;
            }
            sap.Certificate = certa[0];
            if(sigtype == CryptoStandard.CADES)
                sap.AddDeveloperExtension(PdfDeveloperExtension.ESIC_1_7_EXTENSIONLEVEL2);
            PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, sigtype == CryptoStandard.CADES ? PdfName.ETSI_CADES_DETACHED : PdfName.ADBE_PKCS7_DETACHED);
            dic.Reason = sap.Reason;
            dic.Location = sap.Location;
            dic.SignatureCreator = sap.SignatureCreator;
            dic.Contact = sap.Contact;
            dic.Date = new PdfDate(sap.SignDate); // time-stamp will over-rule this
            sap.CryptoDictionary = dic;

            Dictionary<PdfName, int> exc = new Dictionary<PdfName, int>();
            exc[PdfName.CONTENTS] = estimatedSize * 2 + 2;
            sap.PreClose(exc);

            String hashAlgorithm = externalSignature.GetHashAlgorithm();
            PdfPKCS7 sgn = new PdfPKCS7(null, chain, hashAlgorithm, false);
            IDigest messageDigest = DigestUtilities.GetDigest(hashAlgorithm);
            Stream data = sap.GetRangeStream();
            byte[] hash = DigestAlgorithms.Digest(data, hashAlgorithm);
            DateTime cal = DateTime.Now;
            byte[] ocsp = null;
            if (chain.Count >= 2 && ocspClient != null) {
                ocsp = ocspClient.GetEncoded(certa[0], certa[1], null);
            }
            byte[] sh = sgn.getAuthenticatedAttributeBytes(hash, cal, ocsp, crlBytes, sigtype);
            byte[] extSignature = externalSignature.Sign(sh);
            sgn.SetExternalDigest(extSignature, null, externalSignature.GetEncryptionAlgorithm());

            byte[] encodedSig = sgn.GetEncodedPKCS7(hash, cal, tsaClient, ocsp, crlBytes, sigtype);

            if (estimatedSize < encodedSig.Length)
                throw new IOException("Not enough space");

            byte[] paddedSig = new byte[estimatedSize];
            System.Array.Copy(encodedSig, 0, paddedSig, 0, encodedSig.Length);

            PdfDictionary dic2 = new PdfDictionary();
            dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true));
            sap.Close(dic2);
        }
Example #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);
        }
        static void addLTVToStream(Stream source, Stream destination, IOcspClient ocsp, ICrlClient crl,
                                   LtvVerification.Level timestampLevel, LtvVerification.Level signatureLevel)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(source),
                                                 new PdfWriter(destination),
                                                 new StampingProperties().UseAppendMode());

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

            IList <string> names   = signatureUtil.GetSignatureNames();
            String         sigName = names[(names.Count - 1)];

            PdfPKCS7 pkcs7 = signatureUtil.ReadSignatureData(sigName);

            if (pkcs7.IsTsp())
            {
                v.AddVerification(sigName, ocsp, crl, LtvVerification.CertificateOption.WHOLE_CHAIN,
                                  timestampLevel, LtvVerification.CertificateInclusion.YES);
            }
            else
            {
                foreach (String name in names)
                {
                    v.AddVerification(name, ocsp, crl, LtvVerification.CertificateOption.WHOLE_CHAIN,
                                      signatureLevel, LtvVerification.CertificateInclusion.YES);
                }
            }

            v.Merge();
            pdfDoc.Close();
        }
Example #8
0
        public static bool SignHashed(string Source, string Target, SysX509.X509Certificate2 Certificate, string Reason, string Location, bool AddVisibleSign, bool AddTimeStamp, string strTSA)
        {
            PdfReader  objReader  = null;
            PdfStamper objStamper = null;

            try
            {
                X509CertificateParser objCP    = new Org.BouncyCastle.X509.X509CertificateParser();
                X509Certificate[]     objChain = new X509Certificate[] { objCP.ReadCertificate(Certificate.RawData) };

                IList <ICrlClient> crlList = new List <ICrlClient>();
                crlList.Add(new CrlClientOnline(objChain));

                objReader  = new PdfReader(Source);
                objStamper = PdfStamper.CreateSignature(objReader, new FileStream(Target, FileMode.Create), '\0', null, true);

                // Creamos la apariencia
                PdfSignatureAppearance signatureAppearance = objStamper.SignatureAppearance;
                signatureAppearance.Reason = "Inforegistro, S.L.";
                //signatureAppearance.Location = Location;

                // Custom signature appearance text
                var font = FontFactory.GetFont("Times New Roman", 11, iTextSharp.text.Font.BOLDITALIC, BaseColor.DARK_GRAY);
                signatureAppearance.Layer2Font = font;
                signatureAppearance.Layer2Text = "Firmado digitalmente por \r\nInforegistro, S.L.\r\nFecha  " + DateTime.Now.ToShortDateString();
                var rectangle = new Rectangle(350, 30, 500, 120);

                // Si está la firma visible:
                if (AddVisibleSign)
                {
                    signatureAppearance.SetVisibleSignature(rectangle, 2, "Inforegistro");
                }

                ITSAClient  tsaClient  = null;
                IOcspClient ocspClient = null;

                // Creating the signature
                IExternalSignature externalSignature = new X509Certificate2Signature(Certificate, "SHA-1");
                MakeSignature.SignDetached(signatureAppearance, externalSignature, objChain, crlList, ocspClient, tsaClient, 0, CryptoStandard.CMS);
                return(File.Exists(Target));
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (objReader != null)
                {
                    objReader.Close();
                }
                if (objStamper != null)
                {
                    objStamper.Close();
                }
            }
        }
        public AzureKeyVaultSigner(AzureKeyVaultClient keyVaultClient, string certificateIdentifier, string keyId, string keyVaultUri, ITsaClient tsaClient = null,
                                   IOcspClient ocspClient      = null, ICrlClient crlClient = null,
                                   PdfSignatureProfile profile = PdfSignatureProfile.Pdf) : base(tsaClient, ocspClient, crlClient, profile)
        {
            this.keyVaultClient = keyVaultClient;
            this.keyId          = keyId;

            // Get certificate (without a public key) from Azure Key Vault storage
            // or create a new one at runtime
            // You can get the whole certificate chain here
            certificateChain = new byte[][] { keyVaultClient.GetCertificateData(keyVaultUri, certificateIdentifier) };
        }
Example #10
0
        /// <summary>
        /// Firma un documento PDF
        /// </summary>
        /// <param name="Source">Path del PDF a firmar</param>
        /// <param name="Target">Path del PDF firmado</param>
        /// <param name="Certificate">Certificado para realizar la firma</param>
        /// <param name="Reason">Motivo</param>
        /// <param name="Location">Ubicación</param>
        /// <param name="AddVisibleSign">Indica si la firma es visible dentro del documento</param>
        /// <param name="AddTimeStamp">Indica si se va a añadir sello de tiempo en el documento</param>
        /// <param name="strTSA">TSA del sello de tiempo</param>

        public static void SignHashed(string Source, string Target, SysX509.X509Certificate2 Certificate, string Reason, string Location, bool AddVisibleSign, bool AddTimeStamp, string strTSA)
        {
            X509CertificateParser objCP = new X509CertificateParser();

            X509Certificate[] objChain = new X509Certificate[] { objCP.ReadCertificate(Certificate.RawData) };

            //IList<ICrlClient> crlList = new List<ICrlClient>();
            //crlList.Add(new CrlClientOnline(objChain));

            PdfReader  objReader  = new PdfReader(Source);
            PdfStamper objStamper = PdfStamper.CreateSignature(objReader, new FileStream(Target, FileMode.Create), '\0', null, true);

            // Creamos la apariencia
            PdfSignatureAppearance signatureAppearance = objStamper.SignatureAppearance;

            signatureAppearance.Reason   = Reason;
            signatureAppearance.Location = Location;

            // Si está la firma visible:
            if (AddVisibleSign)
            {
                signatureAppearance.SetVisibleSignature(new Rectangle(100, 100, 300, 200), 1, null); //signatureAppearance.SetVisibleSignature(new Rectangle(100, 100, 250, 150), objReader.NumberOfPages, "Signature");
            }
            ITSAClient  tsaClient  = null;
            IOcspClient ocspClient = null;

            // Si se ha añadido el sello de tiempo
            if (AddTimeStamp)
            {
                //  ocspClient = new OcspClientBouncyCastle();
                tsaClient = new TSAClientBouncyCastle(strTSA);
            }

            // Creating the signature
            //  IExternalSignature externalSignature = new X509Certificate2Signature(Certificate, "SHA-1");
            //  MakeSignature.SignDetached(signatureAppearance, externalSignature, objChain, crlList, ocspClient, tsaClient, 0, CryptoStandard.CMS);

            if (objReader != null)
            {
                objReader.Close();
            }
            if (objStamper != null)
            {
                objStamper.Close();
            }
        }
        /**
         * Call this method to have LTV information added to the {@link PdfStamper}
         * given in the constructor.
         */
        public void enable(IOcspClient ocspClient, ICrlClient crlClient)
        {
            AcroFields fields    = pdfStamper.AcroFields;
            bool       encrypted = pdfStamper.Reader.IsEncrypted();

            List <String> names = fields.GetSignatureNames();

            foreach (String name in names)
            {
                PdfPKCS7        pdfPKCS7            = fields.VerifySignature(name);
                PdfDictionary   signatureDictionary = fields.GetSignatureDictionary(name);
                X509Certificate certificate         = pdfPKCS7.SigningCertificate;
                addLtvForChain(certificate, ocspClient, crlClient, getSignatureHashKey(signatureDictionary, encrypted));
            }

            outputDss();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="src"></param>
        /// <param name="dest"></param>
        /// <param name="ocsp"></param>
        /// <param name="crl"></param>
        private static void AddLtv(byte[] src, String dest, IOcspClient ocsp, ICrlClient crl)
        {
            var r = new PdfReader(src);
            var fos = new FileStream(dest, FileMode.Create);
            var stp = new PdfStamper(r, fos, '\0', true);
            LtvVerification v = stp.LtvVerification;
            AcroFields fields = stp.AcroFields;
            List<String> names = fields.GetSignatureNames();
            String sigName = names[names.Count - 1];
            PdfPKCS7 pkcs7 = fields.VerifySignature(sigName);
            if (pkcs7.IsTsp)
                v.AddVerification(sigName, ocsp, crl, LtvVerification.CertificateOption.SIGNING_CERTIFICATE, LtvVerification.Level.OCSP_CRL, LtvVerification.CertificateInclusion.NO);
            else
                foreach (String name in names)
                    v.AddVerification(name, ocsp, crl, LtvVerification.CertificateOption.WHOLE_CHAIN, LtvVerification.Level.OCSP_CRL, LtvVerification.CertificateInclusion.NO);

            stp.Close();
        }
        //
        // the actual LTV enabling methods
        //
        void addLtvForChain(X509Certificate certificate, IOcspClient ocspClient, ICrlClient crlClient, PdfName key)
        {
            if (seenCertificates.Contains(certificate))
            {
                return;
            }
            seenCertificates.Add(certificate);
            ValidationData validationData = new ValidationData();

            while (certificate != null)
            {
                // Console.WriteLine(certificate.SubjectDN);
                X509Certificate issuer = getIssuerCertificate(certificate);
                validationData.certs.Add(certificate.GetEncoded());
                byte[] ocspResponse = ocspClient.GetEncoded(certificate, issuer, null);
                if (ocspResponse != null)
                {
                    // Console.WriteLine("  with OCSP response");
                    validationData.ocsps.Add(ocspResponse);
                    X509Certificate ocspSigner = getOcspSignerCertificate(ocspResponse);
                    ////if (ocspSigner != null)
                    ////{
                    ////    Console.WriteLine("  signed by {0}\n", ocspSigner.SubjectDN);
                    ////}
                    addLtvForChain(ocspSigner, ocspClient, crlClient, getOcspHashKey(ocspResponse));
                }
                else
                {
                    ICollection <byte[]> crl = crlClient.GetEncoded(certificate, null);
                    if (crl != null && crl.Count > 0)
                    {
                        //Console.WriteLine("  with {0} CRLs\n", crl.Count);
                        foreach (byte[] crlBytes in crl)
                        {
                            validationData.crls.Add(crlBytes);
                            addLtvForChain(null, ocspClient, crlClient, getCrlHashKey(crlBytes));
                        }
                    }
                }
                certificate = issuer;
            }

            validated[key] = validationData;
        }
Example #14
0
        public void Sign(String src, String dest,
                         ICollection <X509Certificate> chain, X509Certificate2 pk,
                         String digestAlgorithm, CryptoStandard subfilter,
                         String reason, String location,
                         ICollection <ICrlClient> crlList,
                         IOcspClient ocspClient,
                         ITSAClient tsaClient,
                         int estimatedSize)
        {
            // Creating the reader and the stamper
            PdfReader  reader  = null;
            PdfStamper stamper = null;
            FileStream os      = null;

            try {
                reader  = new PdfReader(src);
                os      = new FileStream(dest, FileMode.Create);
                stamper = PdfStamper.CreateSignature(reader, os, '\0');
                // Creating the appearance
                PdfSignatureAppearance appearance = stamper.SignatureAppearance;
                appearance.Reason   = reason;
                appearance.Location = location;
                appearance.SetVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig");
                // Creating the signature
                IExternalSignature pks = new X509Certificate2Signature(pk, digestAlgorithm);
                MakeSignature.SignDetached(appearance, pks, chain, crlList, ocspClient, tsaClient, estimatedSize,
                                           subfilter);
            }
            finally {
                if (reader != null)
                {
                    reader.Close();
                }
                if (stamper != null)
                {
                    stamper.Close();
                }
                if (os != null)
                {
                    os.Close();
                }
            }
        }
Example #15
0
        private static byte[] AddPdfSignatureField(byte[] src,
                                                   ICollection <Org.BouncyCastle.X509.X509Certificate> chain, X509Certificate2 pk,
                                                   string digestAlgorithm, CryptoStandard subfilter,
                                                   string reason, string location,
                                                   ICollection <ICrlClient> crlList,
                                                   IOcspClient ocspClient,
                                                   ITSAClient tsaClient,
                                                   int estimatedSize, int page, Rectangle rectangle, string signatureFieldName)
        {
            // Creating the reader and the stamper
            PdfReader  reader  = null;
            PdfStamper stamper = null;
            var        os      = new MemoryStream();

            try
            {
                reader  = new PdfReader(src);
                stamper = PdfStamper.CreateSignature(reader, os, '\0');
                // Creating the appearance
                var appearance = stamper.SignatureAppearance;
                appearance.Reason   = reason;
                appearance.Location = location;
                appearance.SetVisibleSignature(rectangle, page, signatureFieldName);
                // Creating the signature
                IExternalSignature pks = new X509Certificate2Signature(pk, digestAlgorithm);
                MakeSignature.SignDetached(appearance, pks, chain, crlList, ocspClient, tsaClient, estimatedSize,
                                           subfilter);
                return(os.ToArray());
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (stamper != null)
                {
                    stamper.Close();
                }
            }
        }
Example #16
0
        private void MontarEstruturaCertificacao(X509Certificate2 certificate)
        {
            this.chain = this.GetChain(certificate);

            foreach (var cadeia in this.chain)
            {
                Log.Application.Debug(cadeia.ToString());
            }

            Log.Application.Debug("Conseguiu pegar valor da cadeia? " + this.chain != null);

            this.ocspClient = new OcspClientBouncyCastle(null);

            this.crlList = new List <ICrlClient>
            {
                new CrlClientOnline(this.chain)
            };

            this.tsaClient = this.GetTsaClient(this.chain);

            Log.Application.Debug("Conseguiu pegar valor da autoridade de tempo? " + this.tsaClient != null);
        }
Example #17
0
 /**
  * Add verification for a particular signature
  * @param signatureName the signature to validate (it may be a timestamp)
  * @param ocsp the interface to get the OCSP
  * @param crl the interface to get the CRL
  * @param certOption
  * @param level the validation options to include
  * @param certInclude
  * @return true if a validation was generated, false otherwise
  * @throws Exception
  */
 virtual public bool AddVerification(String signatureName, IOcspClient ocsp, ICrlClient crl, CertificateOption certOption, Level level, CertificateInclusion certInclude) {
     if (used)
         throw new InvalidOperationException(MessageLocalization.GetComposedMessage("verification.already.output"));
     PdfPKCS7 pk = acroFields.VerifySignature(signatureName);
     LOGGER.Info("Adding verification for " + signatureName);
     X509Certificate[] xc = pk.Certificates;
     X509Certificate cert;
     X509Certificate signingCert = pk.SigningCertificate;
     ValidationData vd = new ValidationData();
     for (int k = 0; k < xc.Length; ++k) {
         cert = xc[k];
         LOGGER.Info("Certificate: " + cert.SubjectDN);
         if (certOption == CertificateOption.SIGNING_CERTIFICATE
             && !cert.Equals(signingCert)) {
             continue;
         }
         byte[] ocspEnc = null;
         if (ocsp != null && level != Level.CRL) {
             ocspEnc = ocsp.GetEncoded(cert, GetParent(cert, xc), null);
             if (ocspEnc != null) {
                 vd.ocsps.Add(BuildOCSPResponse(ocspEnc));
                 LOGGER.Info("OCSP added");
             }
         }
         if (crl != null && (level == Level.CRL || level == Level.OCSP_CRL || (level == Level.OCSP_OPTIONAL_CRL && ocspEnc == null))) {
             ICollection<byte[]> cims = crl.GetEncoded(xc[k], null);
             if (cims != null) {
                 foreach (byte[] cim in cims) {
                     bool dup = false;
                     foreach (byte[] b in vd.crls) {
                         if (Arrays.AreEqual(b, cim)) {
                             dup = true;
                             break;
                         }
                     }
                     if (!dup) {
                         vd.crls.Add(cim);
                         LOGGER.Info("CRL added");
                     }
                 }
             }
         }
         if (certInclude == CertificateInclusion.YES) {
             vd.certs.Add(xc[k].GetEncoded());
         }
     }
     if (vd.crls.Count == 0 && vd.ocsps.Count == 0)
         return false;
     validated[GetSignatureHashKey(signatureName)] = vd;
     return true;
 }
Example #18
0
 private void addVerificationInfo(IOcspClient ocspClient, LtvVerification verification, CrlClientOnline crl, String name)
 {
     verification.AddVerification(name, ocspClient, crl, LtvVerification.CertificateOption.WHOLE_CHAIN, LtvVerification.Level.OCSP_CRL, LtvVerification.CertificateInclusion.YES);
 }
        /**
         * Signs the document using the detached mode, CMS or CAdES equivalent.
         * @param sap the PdfSignatureAppearance
         * @param externalSignature the interface providing the actual signing
         * @param chain the certificate chain
         * @param crlList the CRL list
         * @param ocspClient the OCSP client
         * @param tsaClient the Timestamp client
         * @param provider the provider or null
         * @param estimatedSize the reserved size for the signature. It will be estimated if 0
         * @param cades true to sign CAdES equivalent PAdES-BES, false to sign CMS
         * @throws DocumentException
         * @throws IOException
         * @throws GeneralSecurityException
         * @throws NoSuchAlgorithmException
         * @throws Exception
         */
        public static void SignDetached(PdfSignatureAppearance sap, IExternalSignature externalSignature, ICollection <X509Certificate> chain, ICollection <ICrlClient> crlList, IOcspClient ocspClient,
                                        ITSAClient tsaClient, int estimatedSize, CryptoStandard sigtype)
        {
            List <X509Certificate> certa    = new List <X509Certificate>(chain);
            ICollection <byte[]>   crlBytes = null;
            int i = 0;

            while (crlBytes == null && i < certa.Count)
            {
                crlBytes = ProcessCrl(certa[i++], crlList);
            }
            if (estimatedSize == 0)
            {
                estimatedSize = 8192;
                if (crlBytes != null)
                {
                    foreach (byte[] element in crlBytes)
                    {
                        estimatedSize += element.Length + 10;
                    }
                }
                if (ocspClient != null)
                {
                    estimatedSize += 4192;
                }
                if (tsaClient != null)
                {
                    estimatedSize += 4192;
                }
            }
            sap.Certificate = certa[0];
            PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, sigtype == CryptoStandard.CADES ? PdfName.ETSI_CADES_DETACHED : PdfName.ADBE_PKCS7_DETACHED);

            dic.Reason           = sap.Reason;
            dic.Location         = sap.Location;
            dic.Contact          = sap.Contact;
            dic.Date             = new PdfDate(sap.SignDate); // time-stamp will over-rule this
            sap.CryptoDictionary = dic;

            Dictionary <PdfName, int> exc = new Dictionary <PdfName, int>();

            exc[PdfName.CONTENTS] = estimatedSize * 2 + 2;
            sap.PreClose(exc);

            String   hashAlgorithm = externalSignature.GetHashAlgorithm();
            PdfPKCS7 sgn           = new PdfPKCS7(null, chain, hashAlgorithm, false);
            IDigest  messageDigest = DigestUtilities.GetDigest(hashAlgorithm);
            Stream   data          = sap.GetRangeStream();

            byte[]   hash = DigestAlgorithms.Digest(data, hashAlgorithm);
            DateTime cal  = DateTime.Now;

            byte[] ocsp = null;
            if (chain.Count >= 2 && ocspClient != null)
            {
                ocsp = ocspClient.GetEncoded(certa[0], certa[1], null);
            }
            byte[] sh           = sgn.getAuthenticatedAttributeBytes(hash, cal, ocsp, crlBytes, sigtype);
            byte[] extSignature = externalSignature.Sign(sh);
            sgn.SetExternalDigest(extSignature, null, externalSignature.GetEncryptionAlgorithm());

            byte[] encodedSig = sgn.GetEncodedPKCS7(hash, cal, tsaClient, ocsp, crlBytes, sigtype);

            if (estimatedSize + 2 < encodedSig.Length)
            {
                throw new IOException("Not enough space");
            }

            byte[] paddedSig = new byte[estimatedSize];
            System.Array.Copy(encodedSig, 0, paddedSig, 0, encodedSig.Length);

            PdfDictionary dic2 = new PdfDictionary();

            dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true));
            sap.Close(dic2);
        }
        public static void GetCertificateProperties(string thumbprint, out IList <X509Certificate> chain, out X509Certificate2 pk, out IOcspClient ocspClient, out ITSAClient tsaClient, out IList <ICrlClient> crlList)
        {
            GetPK(thumbprint, out chain, out pk);

            ocspClient = new OcspClientBouncyCastle();
            tsaClient  = null;
            for (int i = 0; i < chain.Count; i++)
            {
                X509Certificate cert   = chain[i];
                String          tsaUrl = CertificateUtil.GetTSAURL(cert);
                if (tsaUrl != null)
                {
                    tsaClient = new TSAClientBouncyCastle(tsaUrl);
                    break;
                }
            }
            crlList = new List <ICrlClient>();
            crlList.Add(new CrlClientOnline(chain));
        }
Example #21
0
        /**
         * Add verification for a particular signature
         * @param signatureName the signature to validate (it may be a timestamp)
         * @param ocsp the interface to get the OCSP
         * @param crl the interface to get the CRL
         * @param certOption
         * @param level the validation options to include
         * @param certInclude
         * @return true if a validation was generated, false otherwise
         * @throws Exception
         */
        public bool AddVerification(String signatureName, IOcspClient ocsp, ICrlClient crl, CertificateOption certOption, Level level, CertificateInclusion certInclude)
        {
            if (used)
            {
                throw new InvalidOperationException(MessageLocalization.GetComposedMessage("verification.already.output"));
            }
            PdfPKCS7 pk = acroFields.VerifySignature(signatureName);

            LOGGER.Info("Adding verification for " + signatureName);
            X509Certificate[] xc = pk.Certificates;
            X509Certificate   cert;
            X509Certificate   signingCert = pk.SigningCertificate;
            ValidationData    vd          = new ValidationData();

            for (int k = 0; k < xc.Length; ++k)
            {
                cert = xc[k];
                LOGGER.Info("Certificate: " + cert.SubjectDN);
                if (certOption == CertificateOption.SIGNING_CERTIFICATE &&
                    !cert.Equals(signingCert))
                {
                    continue;
                }
                byte[] ocspEnc = null;
                if (ocsp != null && level != Level.CRL)
                {
                    ocspEnc = ocsp.GetEncoded(cert, GetParent(cert, xc), null);
                    if (ocspEnc != null)
                    {
                        vd.ocsps.Add(BuildOCSPResponse(ocspEnc));
                        LOGGER.Info("OCSP added");
                    }
                }
                if (crl != null && (level == Level.CRL || level == Level.OCSP_CRL || (level == Level.OCSP_OPTIONAL_CRL && ocspEnc == null)))
                {
                    ICollection <byte[]> cims = crl.GetEncoded(xc[k], null);
                    if (cims != null)
                    {
                        foreach (byte[] cim in cims)
                        {
                            bool dup = false;
                            foreach (byte[] b in vd.crls)
                            {
                                if (Arrays.AreEqual(b, cim))
                                {
                                    dup = true;
                                    break;
                                }
                            }
                            if (!dup)
                            {
                                vd.crls.Add(cim);
                                LOGGER.Info("CRL added");
                            }
                        }
                    }
                }
                if (certInclude == CertificateInclusion.YES)
                {
                    vd.certs.Add(xc[k].GetEncoded());
                }
            }
            if (vd.crls.Count == 0 && vd.ocsps.Count == 0)
            {
                return(false);
            }
            validated[GetSignatureHashKey(signatureName)] = vd;
            return(true);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <param name="chain"></param>
        /// <param name="pks"></param>
        /// <param name="subfilter"></param>
        /// <param name="reason"></param>
        /// <param name="location"></param>
        /// <param name="crlList"></param>
        /// <param name="ocspClient"></param>
        /// <param name="tsaClient"></param>
        /// <param name="estimatedSize"></param>
        /// <returns></returns>
        private static byte[] SignDocument(String input,
                         ICollection<Org.BouncyCastle.X509.X509Certificate> chain,
                         IExternalSignature pks,
                         CryptoStandard subfilter,
                         String reason, String location,
                         ICollection<ICrlClient> crlList,
                         IOcspClient ocspClient,
                         ITSAClient tsaClient,
                         int estimatedSize)
        {
            using (var stream = new MemoryStream())
            {
                // Creating the reader and the stamper
                PdfReader reader = null;
                PdfStamper stamper = null;
                try
                {
                    reader = new PdfReader(input);
                    stamper = PdfStamper.CreateSignature(reader, stream, '\0');

                    // Creating the appearance
                    PdfSignatureAppearance appearance = stamper.SignatureAppearance;
                    appearance.Reason = reason;
                    appearance.Location = location;
                    //appearance.SetVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig");

                    // Creating the signature
                    MakeSignature.SignDetached(appearance, pks, chain, crlList, ocspClient, tsaClient, estimatedSize, subfilter);
                }
                finally
                {
                    reader?.Close();
                    stamper?.Close();
                }

                return stream.GetBuffer();
            }
        }
Example #23
0
 /**
  * Add verification for a particular signature
  * @param signatureName the signature to validate (it may be a timestamp)
  * @param ocsp the interface to get the OCSP
  * @param crl the interface to get the CRL
  * @param certOption
  * @param level the validation options to include
  * @param certInclude
  * @return true if a validation was generated, false otherwise
  * @throws Exception
  */
 public bool AddVerification(String signatureName, IOcspClient ocsp, ICrlClient crl, CertificateOption certOption, Level level, CertificateInclusion certInclude) {
     if (used)
         throw new InvalidOperationException(MessageLocalization.GetComposedMessage("verification.already.output"));
     PdfPKCS7 pk = acroFields.VerifySignature(signatureName);
     X509Certificate[] xc = pk.SignCertificateChain;
     ValidationData vd = new ValidationData();
     for (int k = 0; k < xc.Length; ++k) {
         byte[] ocspEnc = null;
         if (ocsp != null && level != Level.CRL && k < xc.Length - 1) {
             ocspEnc = ocsp.GetEncoded(xc[k], xc[k + 1], null);
             if (ocspEnc != null)
                 vd.ocsps.Add(BuildOCSPResponse(ocspEnc));
         }
         if (crl != null && (level == Level.CRL || level == Level.OCSP_CRL || (level == Level.OCSP_OPTIONAL_CRL && ocspEnc == null))) {
             byte[] cim = crl.GetEncoded(xc[k], null);
             if (cim != null) {
                 bool dup = false;
                 foreach (byte[] b in vd.crls) {
                     if (Arrays.AreEqual(b, cim)) {
                         dup = true;
                         break;
                     }
                 }
                 if (!dup)
                     vd.crls.Add(cim);
             }
         }
         if (certOption == CertificateOption.SIGNING_CERTIFICATE)
             break;
     }
     if (vd.crls.Count == 0 && vd.ocsps.Count == 0)
         return false;
     if (certInclude == CertificateInclusion.YES) {
         foreach (X509Certificate c in xc) {
             vd.certs.Add(c.GetEncoded());
         }
     }
     validated[GetSignatureHashKey(signatureName)] = vd;
     return true;
 }
Example #24
0
        /// <summary>Signs the document using the detached mode, CMS or CAdES equivalent.</summary>
        /// <remarks>
        /// Signs the document using the detached mode, CMS or CAdES equivalent.
        /// <br /><br />
        /// NOTE: This method closes the underlying pdf document. This means, that current instance
        /// of PdfSigner cannot be used after this method call.
        /// </remarks>
        /// <param name="externalSignature">the interface providing the actual signing</param>
        /// <param name="chain">the certificate chain</param>
        /// <param name="crlList">the CRL list</param>
        /// <param name="ocspClient">the OCSP client</param>
        /// <param name="tsaClient">the Timestamp client</param>
        /// <param name="externalDigest">an implementation that provides the digest</param>
        /// <param name="estimatedSize">the reserved size for the signature. It will be estimated if 0</param>
        /// <param name="sigtype">Either Signature.CMS or Signature.CADES</param>
        /// <exception cref="System.IO.IOException"/>
        /// <exception cref="Org.BouncyCastle.Security.GeneralSecurityException"/>
        public virtual void SignDetached(IExternalSignature externalSignature, X509Certificate[] chain, ICollection
                                         <ICrlClient> crlList, IOcspClient ocspClient, ITSAClient tsaClient, int estimatedSize, PdfSigner.CryptoStandard
                                         sigtype)
        {
            if (closed)
            {
                throw new PdfException(PdfException.ThisInstanceOfPdfSignerAlreadyClosed);
            }
            ICollection <byte[]> crlBytes = null;
            int i = 0;

            while (crlBytes == null && i < chain.Length)
            {
                crlBytes = ProcessCrl(chain[i++], crlList);
            }
            if (estimatedSize == 0)
            {
                estimatedSize = 8192;
                if (crlBytes != null)
                {
                    foreach (byte[] element in crlBytes)
                    {
                        estimatedSize += element.Length + 10;
                    }
                }
                if (ocspClient != null)
                {
                    estimatedSize += 4192;
                }
                if (tsaClient != null)
                {
                    estimatedSize += 4192;
                }
            }
            PdfSignatureAppearance appearance = GetSignatureAppearance();

            appearance.SetCertificate(chain[0]);
            if (sigtype == PdfSigner.CryptoStandard.CADES)
            {
                AddDeveloperExtension(PdfDeveloperExtension.ESIC_1_7_EXTENSIONLEVEL2);
            }
            PdfSignature dic = new PdfSignature(PdfName.Adobe_PPKLite, sigtype == PdfSigner.CryptoStandard.CADES ? PdfName
                                                .ETSI_CAdES_DETACHED : PdfName.Adbe_pkcs7_detached);

            dic.SetReason(appearance.GetReason());
            dic.SetLocation(appearance.GetLocation());
            dic.SetSignatureCreator(appearance.GetSignatureCreator());
            dic.SetContact(appearance.GetContact());
            dic.SetDate(new PdfDate(GetSignDate()));
            // time-stamp will over-rule this
            cryptoDictionary = dic;
            IDictionary <PdfName, int?> exc = new Dictionary <PdfName, int?>();

            exc[PdfName.Contents] = estimatedSize * 2 + 2;
            PreClose(exc);
            String   hashAlgorithm = externalSignature.GetHashAlgorithm();
            PdfPKCS7 sgn           = new PdfPKCS7((ICipherParameters)null, chain, hashAlgorithm, false);
            Stream   data          = GetRangeStream();

            byte[] hash = DigestAlgorithms.Digest(data, SignUtils.GetMessageDigest(hashAlgorithm));
            byte[] ocsp = null;
            if (chain.Length >= 2 && ocspClient != null)
            {
                ocsp = ocspClient.GetEncoded((X509Certificate)chain[0], (X509Certificate)chain[1], null);
            }
            byte[] sh           = sgn.GetAuthenticatedAttributeBytes(hash, ocsp, crlBytes, sigtype);
            byte[] extSignature = externalSignature.Sign(sh);
            sgn.SetExternalDigest(extSignature, null, externalSignature.GetEncryptionAlgorithm());
            byte[] encodedSig = sgn.GetEncodedPKCS7(hash, tsaClient, ocsp, crlBytes, sigtype);
            if (estimatedSize < encodedSig.Length)
            {
                throw new System.IO.IOException("Not enough space");
            }
            byte[] paddedSig = new byte[estimatedSize];
            System.Array.Copy(encodedSig, 0, paddedSig, 0, encodedSig.Length);
            PdfDictionary dic2 = new PdfDictionary();

            dic2.Put(PdfName.Contents, new PdfString(paddedSig).SetHexWriting(true));
            Close(dic2);
            closed = true;
        }
Example #25
0
        /**
         * Add verification for a particular signature
         * @param signatureName the signature to validate (it may be a timestamp)
         * @param ocsp the interface to get the OCSP
         * @param crl the interface to get the CRL
         * @param certOption
         * @param level the validation options to include
         * @param certInclude
         * @return true if a validation was generated, false otherwise
         * @throws Exception
         */
        public bool AddVerification(String signatureName, IOcspClient ocsp, ICrlClient crl, CertificateOption certOption, Level level, CertificateInclusion certInclude)
        {
            if (used)
            {
                throw new InvalidOperationException(MessageLocalization.GetComposedMessage("verification.already.output"));
            }
            PdfPKCS7 pk = acroFields.VerifySignature(signatureName);

            X509Certificate[] xc = pk.SignCertificateChain;
            ValidationData    vd = new ValidationData();

            for (int k = 0; k < xc.Length; ++k)
            {
                byte[] ocspEnc = null;
                if (ocsp != null && level != Level.CRL && k < xc.Length - 1)
                {
                    ocspEnc = ocsp.GetEncoded(xc[k], xc[k + 1], null);
                    if (ocspEnc != null)
                    {
                        vd.ocsps.Add(BuildOCSPResponse(ocspEnc));
                    }
                }
                if (crl != null && (level == Level.CRL || level == Level.OCSP_CRL || (level == Level.OCSP_OPTIONAL_CRL && ocspEnc == null)))
                {
                    ICollection <byte[]> cims = crl.GetEncoded((X509Certificate)xc[k], null);
                    if (cims != null)
                    {
                        foreach (byte[] cim in cims)
                        {
                            bool dup = false;
                            foreach (byte[] b in vd.crls)
                            {
                                if (Arrays.AreEqual(b, cim))
                                {
                                    dup = true;
                                    break;
                                }
                            }
                            if (!dup)
                            {
                                vd.crls.Add(cim);
                            }
                        }
                    }
                }
                if (certOption == CertificateOption.SIGNING_CERTIFICATE)
                {
                    break;
                }
            }
            if (vd.crls.Count == 0 && vd.ocsps.Count == 0)
            {
                return(false);
            }
            if (certInclude == CertificateInclusion.YES)
            {
                foreach (X509Certificate c in xc)
                {
                    vd.certs.Add(c.GetEncoded());
                }
            }
            validated[GetSignatureHashKey(signatureName)] = vd;
            return(true);
        }
Example #26
0
        /// <summary>Add verification for a particular signature.</summary>
        /// <param name="signatureName">the signature to validate (it may be a timestamp)</param>
        /// <param name="ocsp">the interface to get the OCSP</param>
        /// <param name="crl">the interface to get the CRL</param>
        /// <param name="certOption">options as to how many certificates to include</param>
        /// <param name="level">the validation options to include</param>
        /// <param name="certInclude">certificate inclusion options</param>
        /// <returns>true if a validation was generated, false otherwise</returns>
        /// <exception cref="Org.BouncyCastle.Security.GeneralSecurityException"/>
        /// <exception cref="System.IO.IOException"/>
        public virtual bool AddVerification(String signatureName, IOcspClient ocsp, ICrlClient crl, LtvVerification.CertificateOption
                                            certOption, LtvVerification.Level level, LtvVerification.CertificateInclusion certInclude)
        {
            if (used)
            {
                throw new InvalidOperationException(PdfException.VerificationAlreadyOutput);
            }
            PdfPKCS7 pk = sgnUtil.VerifySignature(signatureName);

            LOGGER.Info("Adding verification for " + signatureName);
            X509Certificate[] xc = pk.GetCertificates();
            X509Certificate   cert;
            X509Certificate   signingCert = pk.GetSigningCertificate();

            LtvVerification.ValidationData vd = new LtvVerification.ValidationData();
            for (int k = 0; k < xc.Length; ++k)
            {
                cert = (X509Certificate)xc[k];
                LOGGER.Info("Certificate: " + cert.SubjectDN);
                if (certOption == LtvVerification.CertificateOption.SIGNING_CERTIFICATE && !cert.Equals(signingCert))
                {
                    continue;
                }
                byte[] ocspEnc = null;
                if (ocsp != null && level != LtvVerification.Level.CRL)
                {
                    ocspEnc = ocsp.GetEncoded(cert, GetParent(cert, xc), null);
                    if (ocspEnc != null)
                    {
                        vd.ocsps.Add(BuildOCSPResponse(ocspEnc));
                        LOGGER.Info("OCSP added");
                    }
                }
                if (crl != null && (level == LtvVerification.Level.CRL || level == LtvVerification.Level.OCSP_CRL || (level
                                                                                                                      == LtvVerification.Level.OCSP_OPTIONAL_CRL && ocspEnc == null)))
                {
                    ICollection <byte[]> cims = crl.GetEncoded(cert, null);
                    if (cims != null)
                    {
                        foreach (byte[] cim in cims)
                        {
                            bool dup = false;
                            foreach (byte[] b in vd.crls)
                            {
                                if (JavaUtil.ArraysEquals(b, cim))
                                {
                                    dup = true;
                                    break;
                                }
                            }
                            if (!dup)
                            {
                                vd.crls.Add(cim);
                                LOGGER.Info("CRL added");
                            }
                        }
                    }
                }
                if (certInclude == LtvVerification.CertificateInclusion.YES)
                {
                    vd.certs.Add(cert.GetEncoded());
                }
            }
            if (vd.crls.Count == 0 && vd.ocsps.Count == 0)
            {
                return(false);
            }
            validated.Put(GetSignatureHashKey(signatureName), vd);
            return(true);
        }
Example #27
0
 /**
  * Signs the document using the detached mode, CMS or CAdES equivalent.
  * @param sap the PdfSignatureAppearance
  * @param externalSignature the interface providing the actual signing
  * @param chain the certificate chain
  * @param crlList the CRL list
  * @param ocspClient the OCSP client
  * @param tsaClient the Timestamp client
  * @param provider the provider or null
  * @param estimatedSize the reserved size for the signature. It will be estimated if 0
  * @param cades true to sign CAdES equivalent PAdES-BES, false to sign CMS
  * @throws DocumentException
  * @throws IOException
  * @throws GeneralSecurityException
  * @throws NoSuchAlgorithmException
  * @throws Exception
  */
 public static void SignDetached(PdfSignatureAppearance sap, IExternalSignature externalSignature,
                                 ICollection <X509Certificate> chain, ICollection <ICrlClient> crlList, IOcspClient ocspClient,
                                 ITSAClient tsaClient, int estimatedSize, CryptoStandard sigtype)
 {
     SignDetached(sap, externalSignature, chain, crlList, ocspClient, tsaClient, estimatedSize, sigtype, (SignaturePolicyIdentifier)null);
 }
Example #28
0
        private static void CreateSignature(SigningCertificates signingCertificates, PdfSignatureAppearance signatureAppearance, ICollection<ICrlClient> clrClients, IOcspClient oscpClient)
        {
            IExternalSignature externalSignature = new X509Certificate2Signature(signingCertificates.X509Certificate2, "SHA-1");

            MakeSignature.SignDetached(signatureAppearance, externalSignature, signingCertificates.FinalChain, clrClients, oscpClient, null, 0, CryptoStandard.CMS);
        }
        private static void CreateSignature(SigningCertificates signingCertificates, PdfSignatureAppearance signatureAppearance, ICollection <ICrlClient> clrClients, IOcspClient oscpClient)
        {
            IExternalSignature externalSignature = new X509Certificate2Signature(signingCertificates.X509Certificate2, "SHA-1");

            MakeSignature.SignDetached(signatureAppearance, externalSignature, signingCertificates.FinalChain, clrClients, oscpClient, null, 0, CryptoStandard.CMS);
        }
Example #30
0
        // metodo principal para el procesamiento de pdfs (firma digital adjuntos metadatos)
        public string SignPdf(
            SignRenderingMode signRenderingMode,
            Funciones.Archivos.Pdf.Dtos.PdfSign.PdfSignRequestDto jsonToProcess,
            string path)
        {
            try
            {
                //var json = File.ReadAllText(path);

                //var jsonToProcess = JsonConvert
                //.DeserializeObject<Funciones.Archivos.Pdf.Dtos.PdfSign.PdfSignRequestDto>(json.Replace("<EOF>", ""));

                _target = jsonToProcess.outPath;
                _fs     = GetPdfStreamFormUrlOrBase64(jsonToProcess.dataUriBase64PdfToSign);

                // conversor de certificados
                var objCP   = new BcX509.X509CertificateParser();
                var crlList = new List <ICrlClient>();

                // buscar el certificado por numero serial
                var certificate = SearchCertificate(jsonToProcess.certificateSerialNumber);
                if (certificate == null)
                {
                    return("No se encontraron certificados para el serial: " + jsonToProcess.certificateSerialNumber);
                }

                // definicion del certificado operable
                var objChain = new BcX509.X509Certificate[] { objCP.ReadCertificate(certificate.RawData) };
                crlList.Add(new CrlClientOnline(objChain));

                //TODO: habilitar la estampa cronologica (Error) (verificar tsa Timestamping Authority)
                // agregamos la estampa cronologica
                #region estampa cronologica
                ITSAClient  tsaClient  = null;
                IOcspClient ocspClient = null;
                if (jsonToProcess.addTimeStamp)
                {
                    ocspClient = new OcspClientBouncyCastle();
                    //CertificateUtil.getTSAURL(Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(certificate));
                    tsaClient = new TSAClientBouncyCastle(jsonToProcess.urlTSA);
                }
                #endregion estampa cronologica

                // cargue del pdf al lector de itextsharp
                var _pdfReader = new PdfReader(_fs);

                // cargue an memoria del pdf
                using (var _wfs = new MemoryStream())
                {
                    // creacion de la firma a partir del lector itextsharp y el pdf en memoria
                    using (var objStamper = PdfStamper.CreateSignature(_pdfReader, _wfs, '\0', null, true))
                    {
                        // Procesar adjuntos
                        var attachmentIndex = 1;
                        (jsonToProcess.dataUriBase64ListOfPdfToAttach as List <FileToAttachDto>).ForEach(
                            (item) =>
                        {
                            //TODO: verificar si no se va a necesitar
                            if (!item.pathOrDataUriBase64.StartsWith("data:"))
                            {
                                var pfs = PdfFileSpecification.FileEmbedded(objStamper.Writer, item.fileDescription, attachmentIndex + "_" + item.fileDescription + ".pdf", null, true);
                                objStamper.Writer.AddFileAttachment("Adjunto número: " + attachmentIndex, pfs);
                            }
                            else
                            {
                                try
                                {
                                    var x   = StreamToByteArray(GetPdfStreamFormUrlOrBase64(item.pathOrDataUriBase64));
                                    var pfs = PdfFileSpecification.FileEmbedded(
                                        objStamper.Writer,
                                        item.fileDescription + ".pdf",
                                        item.fileDescription + ".pdf",
                                        x,
                                        true,
                                        item.mimeType,
                                        null
                                        );
                                    objStamper.Writer.AddFileAttachment("Adjunto número: " + attachmentIndex, pfs);
                                    //.AddFileAttachment("adjunto número: " + attachmentIndex, x, "adjunto_" + attachmentIndex + ".pdf", "adjunto " + attachmentIndex);
                                }
                                catch (Exception exce)
                                {
                                    Console.WriteLine(exce.StackTrace);
                                }
                            }
                            attachmentIndex++;
                        });

                        // definicion de la apariencia de la firma
                        var signatureAppearance = objStamper.SignatureAppearance;
                        // definicion del enum itextsharp a partir del enum parametro local
                        var mode = Enum.Parse(typeof(RenderingMode), signRenderingMode.ToString());
                        signatureAppearance.SignatureRenderingMode = (RenderingMode)mode;
                        signatureAppearance.Reason   = jsonToProcess.reasonToSign;
                        signatureAppearance.Location = jsonToProcess.locationDescription;

                        // agregar marca visual de firma digital
                        #region agregar marca visual firma digital
                        if (jsonToProcess.addVisibleSignMark)
                        {
                            // definicion de imagen desde ruta o base64
                            signatureAppearance.SignatureGraphic = GetImageFormUrlOrBase64(jsonToProcess.dataUriBase64SignImage);
                            // definicion de la firma digital visible
                            signatureAppearance.SetVisibleSignature(
                                new Rectangle(jsonToProcess.visibleSignMarkWidth, jsonToProcess.visibleSignMarkHeight, jsonToProcess.xVisibleSignMarkPosition, jsonToProcess.yVisibleSignMarkPosition),
                                _pdfReader.NumberOfPages,
                                jsonToProcess.visibleSignText);
                        }
                        #endregion agregar marca visual firma digital

                        // Agregar propiedades extendidas
                        objStamper.MoreInfo = (jsonToProcess.metadata as List <MetadataDto>).ToDictionary(x => x.key, x => x.value);

                        //TODO: verificar si no es necesario la utilizacion de XMP manual (actualmente funciona)
                        #region xmp implementacion manual

                        /* objStamper.Writer.CreateXmpMetadata();
                         * var xmp = objStamper.Writer.XmpMetadata;
                         *
                         *
                         * //XMP metadatos
                         * IXmpMeta xmp;
                         * using (var stream = File.OpenRead(@"C:\Users\danie\OneDrive\Escritorio\xmpMetadata.xml"))
                         *  xmp = XmpMetaFactory.Parse(stream);
                         *
                         * foreach (var property in xmp.Properties)
                         * {
                         *  Console.WriteLine($"Path={property.Path} Namespace={property.Namespace} Value={property.Value}");
                         * }
                         *
                         * var serializeOptions = new SerializeOptions();
                         * serializeOptions.UsePlainXmp = true;
                         * var newMetadata = XmpMetaFactory.SerializeToBuffer(xmp, serializeOptions);
                         * objStamper.XmpMetadata = newMetadata;*/
                        #endregion xmp implementacion manual

                        // Firmar digitalmente
                        var externalSignature = new X509Certificate2Signature(certificate, jsonToProcess.certificateHashAlgorithm);
                        MakeSignature.SignDetached(signatureAppearance, externalSignature, objChain, crlList, ocspClient, tsaClient, 0, CryptoStandard.CMS);
                    }
                    var pdfFileTocreate = jsonToProcess.outPath.Replace("json", "pdf");
                    System.IO.File.WriteAllBytes(pdfFileTocreate, _wfs.ToArray());
                    Process.Start(pdfFileTocreate);
                    return(Convert.ToBase64String(_wfs.ToArray()));
                }
            }
            catch (Exception exce)
            {
                WriteToFile(exce.StackTrace);
                WriteToFile(exce.Message);
                return(exce.Message);
            }
        }
    public void Sign(String src, String dest,
                     ICollection <X509Certificate> chain, X509Certificate2 pk,
                     String digestAlgorithm, CryptoStandard subfilter,
                     String reason, String location,
                     ICollection <ICrlClient> crlList,
                     IOcspClient ocspClient,
                     ITSAClient tsaClient,
                     int estimatedSize, int RowIdx, int RowHeight, int x, int y, int NameWidth, int DateWidth,
                     String RevIndex, String RevStep, String Reason, String Name, String Date)
    {
        // Creating the reader and the stamper
        PdfReader  reader  = null;
        PdfStamper stamper = null;
        FileStream os      = null;

        try
        {
            reader = new PdfReader(src);
            os     = new FileStream(dest, FileMode.Create);
            // os = new FileStream(dest, FileMode.Create, FileAccess.Write);
            //Activate MultiSignatures
            stamper = PdfStamper.CreateSignature(reader, os, '\0', null, true);
            //To disable Multi signatures uncomment this line : every new signature will invalidate older ones !
            //stamper = PdfStamper.CreateSignature(reader, os, '\0');
            // Creating the appearance
            PdfSignatureAppearance appearance = stamper.SignatureAppearance;
            Rectangle rectangle = new Rectangle(x, y + RowIdx * RowHeight, x + NameWidth + DateWidth, y + (RowIdx + 1) * RowHeight);
            appearance.SetVisibleSignature(rectangle, 1, "Revision " + RevIndex + "|" + RevStep);
            appearance.Reason                 = "marked as changed";
            appearance.Location               = location;
            appearance.Layer2Text             = "Signed on " + DateTime.Now;
            appearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION;
            PdfTemplate n2   = appearance.GetLayer(2);
            Font        font = new Font();
            font.SetColor(255, 0, 0);
            font.Size = 10;
            ColumnText ct1 = new ColumnText(n2);
            ct1.SetSimpleColumn(new Phrase(Name, font), 0, 0, NameWidth, rectangle.Height, 15, Element.ALIGN_LEFT);
            ct1.Go();
            ColumnText ct2 = new ColumnText(n2);
            ct2.SetSimpleColumn(new Phrase(Date, font), NameWidth, 0, rectangle.Width, rectangle.Height, 15, Element.ALIGN_LEFT);
            ct2.Go();
            //n2.ConcatCTM(1, 0, 0, -1, 0, 0);
            //n2.SaveState();
            // Creating the signature
            IExternalSignature pks = new X509Certificate2Signature(pk, digestAlgorithm);
            MakeSignature.SignDetached(appearance, pks, chain, crlList, ocspClient, tsaClient, estimatedSize, subfilter);
        }
        catch (Exception ex)
        {
            Console.WriteLine("GMA: " + ex.Message);
        }
        finally
        {
            if (reader != null)
            {
                reader.Close();
            }
            if (stamper != null)
            {
                stamper.Close();
            }
            if (os != null)
            {
                os.Close();
            }
        }
    }
Example #32
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();
        }