Esempio n. 1
1
        /**
         * Signs a document with a PAdES-LTV Timestamp. The document is closed at the end.
         * @param sap the signature appearance
         * @param tsa the timestamp generator
         * @param signatureName the signature name or null to have a name generated
         * automatically
         * @throws Exception
         */
        public static void Timestamp(PdfSignatureAppearance sap, ITSAClient tsa, String signatureName) {
            int contentEstimated = tsa.GetTokenSizeEstimate();
            sap.SetVisibleSignature(new Rectangle(0,0,0,0), 1, signatureName);

            PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ETSI_RFC3161);
            dic.Put(PdfName.TYPE, PdfName.DOCTIMESTAMP);
            sap.CryptoDictionary = dic;

            Dictionary<PdfName,int> exc = new Dictionary<PdfName,int>();
            exc[PdfName.CONTENTS] = contentEstimated * 2 + 2;
            sap.PreClose(exc);
            Stream data = sap.RangeStream;
            IDigest messageDigest = DigestUtilities.GetDigest(tsa.GetDigestAlgorithm());
            byte[] buf = new byte[4096];
            int n;
            while ((n = data.Read(buf, 0, buf.Length)) > 0) {
                messageDigest.BlockUpdate(buf, 0, n);
            }
            byte[] tsImprint = new byte[messageDigest.GetDigestSize()];
            messageDigest.DoFinal(tsImprint, 0);
            byte[] tsToken = tsa.GetTimeStampToken(tsImprint);

            if (contentEstimated + 2 < tsToken.Length)
                throw new Exception("Not enough space");

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

            PdfDictionary dic2 = new PdfDictionary();
            dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true));
            sap.Close(dic2);
        }
 public HomeController(IAirplaneClient airplanes, IAirplaneRepository airplaneRepository, ITSAClient airportClient, IAirportCodeClient airportCodeClient)
 {
     _airplanes          = airplanes;
     _airplaneRepository = airplaneRepository;
     _airportClient      = airportClient;
     _airportCodeClient  = airportCodeClient;
 }
Esempio n. 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();
        }
Esempio n. 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);
        }
        public void testSignSimpleECDsa()
        {
            string testFileName = @"..\..\..\resources\circles.pdf";
            string storePath    = @"..\..\..\..\simple\keystore\test1234.p12";

            char[] storePass  = "******".ToCharArray();
            string storeAlias = "ECDSAkey";

            Pkcs12Store            pkcs12 = new Pkcs12Store(new FileStream(storePath, FileMode.Open, FileAccess.Read), storePass);
            AsymmetricKeyParameter key    = pkcs12.GetKey(storeAlias).Key;

            X509CertificateEntry[] chainEntries = pkcs12.GetCertificateChain(storeAlias);
            X509Certificate[]      chain        = new X509Certificate[chainEntries.Length];
            for (int i = 0; i < chainEntries.Length; i++)
            {
                chain[i] = chainEntries[i].Certificate;
            }
            PrivateKeySignature signature = new PrivateKeySignature(key, "SHA512");

            using (PdfReader pdfReader = new PdfReader(testFileName))
                using (FileStream result = File.Create("circles-ECDSA-BC-signed-simple.pdf"))
                {
                    PdfSigner  pdfSigner = new PdfSigner(pdfReader, result, new StampingProperties().UseAppendMode());
                    ITSAClient tsaClient = null;

                    pdfSigner.SignDetached(signature, chain, null, null, tsaClient, 0, PdfSigner.CryptoStandard.CMS);
                }
        }
Esempio n. 7
0
        public void testSignSimpleECDsa()
        {
            string testFileName = @"..\..\..\resources\circles.pdf";
            string storePath    = @"..\..\..\..\simple\keystore\test1234.p12";
            string storePass    = "******";
            string storeAlias   = "ECDSAkey";

            SystemCertificates.X509Certificate2Collection pkcs12 = new SystemCertificates.X509Certificate2Collection();
            pkcs12.Import(storePath, storePass, SystemCertificates.X509KeyStorageFlags.DefaultKeySet);
            SystemCertificates.X509Certificate2 certificate = null;
            foreach (SystemCertificates.X509Certificate2 aCertificate in pkcs12)
            {
                if (storeAlias.Equals(aCertificate.FriendlyName, StringComparison.InvariantCultureIgnoreCase))
                {
                    certificate = aCertificate;
                    break;
                }
            }
            Assert.NotNull(certificate, "Key with alias {0} not found.", storeAlias);

            X509Certificate bcCertificate = new X509Certificate(X509CertificateStructure.GetInstance(certificate.RawData));

            X509Certificate[] chain = { bcCertificate };

            X509Certificate2Signature signature = new X509Certificate2Signature(certificate, "SHA512");

            using (PdfReader pdfReader = new PdfReader(testFileName))
                using (FileStream result = File.Create("circles-ECDSA-signed-simple.pdf"))
                {
                    PdfSigner  pdfSigner = new PdfSigner(pdfReader, result, new StampingProperties().UseAppendMode());
                    ITSAClient tsaClient = null;

                    pdfSigner.SignDetached(signature, chain, null, null, tsaClient, 0, PdfSigner.CryptoStandard.CMS);
                }
        }
Esempio n. 8
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);
        }
 public HomeController(IAirplaneClient airplanes, IAirplaneRepository airplaneRepository, ITSAClient airportClient, IAirportCodeClient airportCodeClient, IOptions <APISecretConfig> googleClient)
 {
     _airplanes          = airplanes;
     _airplaneRepository = airplaneRepository;
     _airportClient      = airportClient;
     _airportCodeClient  = airportCodeClient;
     _googleClient       = googleClient.Value.GoogleKey;
 }
Esempio n. 10
0
        public Cert(byte[] rawData, string cpassword, string tsaURL, string tsaLogin, string tsaPwd)
        {
            this.rawData = rawData;
            this.Password = cpassword;
            this.processCert();

            if (tsaURL == null) this.tsc = null;
            else this.tsc = new TSAClientBouncyCastle(tsaURL, tsaLogin, tsaPwd);
        }
Esempio n. 11
0
        public Cert(string cpath, string cpassword, string tsaURL, string tsaLogin, string tsaPwd)
        {
            this.path = cpath;
            this.Password = cpassword;
            this.processCert();

            if (tsaURL == null) this.tsc = null;
            else this.tsc = new TSAClientBouncyCastle(tsaURL, tsaLogin, tsaPwd);
        }
Esempio n. 12
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();
                }
            }
        }
Esempio n. 13
0
 // -------------------------------------------------------------------------------------------------------------------------------- //
 // CONSTRUCTOR METHOD                                                                                                               //
 // -------------------------------------------------------------------------------------------------------------------------------- //
 /// <summary>
 ///
 /// </summary>
 /// <param name="credentials"></param>
 public SdsTsaPdfClient(TsaCredentials credentials)
 {
     if (credentials != null)
     {
         tsaCredentials = credentials;
         tsaClient      = new TSAClientBouncyCastle(Credentials.TsaUrl, Credentials.UserId, Credentials.Password, 3000, Credentials.TimeStampDigestAlg);
     } // IF ENDS
     else
     {
         throw new ArgumentNullException(nameof(credentials));
     } // ELSE ENDS
 }     // CONSTRUCTOR METHOD ENDS ------------------------------------------------------------------------------------------------------ //
Esempio n. 14
0
        public static void Main(String[] args)
        {
            LoggerFactory.GetInstance().SetLogger(new SysoLogger());


            X509Store x509Store = new X509Store("My");

            x509Store.Open(OpenFlags.ReadOnly);
            X509Certificate2Collection certificates = x509Store.Certificates;
            IList <X509Certificate>    chain        = new List <X509Certificate>();
            X509Certificate2           pk           = null;

            if (certificates.Count > 0)
            {
                X509Certificate2Enumerator certificatesEn = certificates.GetEnumerator();
                certificatesEn.MoveNext();
                pk = certificatesEn.Current;

                X509Chain x509chain = new X509Chain();
                x509chain.Build(pk);

                foreach (X509ChainElement x509ChainElement in x509chain.ChainElements)
                {
                    chain.Add(DotNetUtilities.FromX509Certificate(x509ChainElement.Certificate));
                }
            }
            x509Store.Close();


            IOcspClient ocspClient = new OcspClientBouncyCastle();
            ITSAClient  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;
                }
            }
            IList <ICrlClient> crlList = new List <ICrlClient>();

            crlList.Add(new CrlClientOnline(chain));
            C3_11_SignWithToken app = new C3_11_SignWithToken();

            app.Sign(SRC, DEST, chain, pk, DigestAlgorithms.SHA256, CryptoStandard.CMS, "Test",
                     "Ghent",
                     crlList, ocspClient, tsaClient, 0);
        }
Esempio n. 15
0
        public void TestPkcs11SignSimple()
        {
            string testFileName = @"..\..\..\resources\circles.pdf";

            using (Pkcs11Signature signature = new Pkcs11Signature(@"PKCS11LIBRARY", 1).Select("KEYALIAS", "CERTLABEL", "1234").SetHashAlgorithm("SHA256"))
                using (PdfReader pdfReader = new PdfReader(testFileName))
                    using (FileStream result = File.Create("circles-pkcs11-signed-simple.pdf"))
                    {
                        PdfSigner  pdfSigner = new PdfSigner(pdfReader, result, new StampingProperties().UseAppendMode());
                        ITSAClient tsaClient = null;

                        pdfSigner.SignDetached(signature, signature.GetChain(), null, null, tsaClient, 0, CryptoStandard.CMS);
                    }
        }
Esempio n. 16
0
        /**
         * Signs a document with a PAdES-LTV Timestamp. The document is closed at the end.
         * @param sap the signature appearance
         * @param tsa the timestamp generator
         * @param signatureName the signature name or null to have a name generated
         * automatically
         * @throws Exception
         */
        public static void Timestamp(PdfSignatureAppearance sap, ITSAClient tsa, String signatureName)
        {
            int contentEstimated = tsa.GetTokenSizeEstimate();

            sap.AddDeveloperExtension(PdfDeveloperExtension.ESIC_1_7_EXTENSIONLEVEL5);
            sap.SetVisibleSignature(new Rectangle(0, 0, 0, 0), 1, signatureName);

            PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ETSI_RFC3161);

            dic.Put(PdfName.TYPE, PdfName.DOCTIMESTAMP);
            sap.CryptoDictionary = dic;

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

            exc[PdfName.CONTENTS] = contentEstimated * 2 + 2;
            sap.PreClose(exc);
            Stream  data          = sap.GetRangeStream();
            IDigest messageDigest = tsa.GetMessageDigest();

            byte[] buf = new byte[4096];
            int    n;

            while ((n = data.Read(buf, 0, buf.Length)) > 0)
            {
                messageDigest.BlockUpdate(buf, 0, n);
            }
            byte[] tsImprint = new byte[messageDigest.GetDigestSize()];
            messageDigest.DoFinal(tsImprint, 0);
            byte[] tsToken;
            try {
                tsToken = tsa.GetTimeStampToken(tsImprint);
            }
            catch (Exception e) {
                throw new GeneralSecurityException(e.Message);
            }
            //TODO jbonilla Validar para el TSA de Certificado que devuelve un valor muy grande.
            if (contentEstimated + 2 < tsToken.Length)
            {
                throw new IOException("Not enough space");
            }

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

            PdfDictionary dic2 = new PdfDictionary();

            dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true));
            sap.Close(dic2);
        }
Esempio n. 17
0
        public Cert(string cpath, string cpassword, string tsaURL, string tsaLogin, string tsaPwd)
        {
            this.path     = cpath;
            this.Password = cpassword;
            this.processCert();

            if (tsaURL == null)
            {
                this.tsc = null;
            }
            else
            {
                this.tsc = new TSAClientBouncyCastle(tsaURL, tsaLogin, tsaPwd);
            }
        }
Esempio n. 18
0
        public Cert(byte[] rawData, string cpassword, string tsaURL, string tsaLogin, string tsaPwd)
        {
            this.rawData  = rawData;
            this.Password = cpassword;
            this.processCert();

            if (tsaURL == null)
            {
                this.tsc = null;
            }
            else
            {
                this.tsc = new TSAClientBouncyCastle(tsaURL, tsaLogin, tsaPwd);
            }
        }
Esempio n. 19
0
        /// <summary>Signs a document with a PAdES-LTV Timestamp.</summary>
        /// <remarks>
        /// Signs a document with a PAdES-LTV Timestamp. The document is closed at the end.
        /// <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="tsa">the timestamp generator</param>
        /// <param name="signatureName">
        /// the signature name or null to have a name generated
        /// automatically
        /// </param>
        /// <exception cref="System.IO.IOException"/>
        /// <exception cref="Org.BouncyCastle.Security.GeneralSecurityException"/>
        public virtual void Timestamp(ITSAClient tsa, String signatureName)
        {
            if (closed)
            {
                throw new PdfException(PdfException.ThisInstanceOfPdfSignerAlreadyClosed);
            }
            int contentEstimated = tsa.GetTokenSizeEstimate();

            AddDeveloperExtension(PdfDeveloperExtension.ESIC_1_7_EXTENSIONLEVEL5);
            SetFieldName(signatureName);
            PdfSignature dic = new PdfSignature(PdfName.Adobe_PPKLite, PdfName.ETSI_RFC3161);

            dic.Put(PdfName.Type, PdfName.DocTimeStamp);
            cryptoDictionary = dic;
            IDictionary <PdfName, int?> exc = new Dictionary <PdfName, int?>();

            exc[PdfName.Contents] = contentEstimated * 2 + 2;
            PreClose(exc);
            Stream  data          = GetRangeStream();
            IDigest messageDigest = tsa.GetMessageDigest();

            byte[] buf = new byte[4096];
            int    n;

            while ((n = data.Read(buf)) > 0)
            {
                messageDigest.Update(buf, 0, n);
            }
            byte[] tsImprint = messageDigest.Digest();
            byte[] tsToken;
            try {
                tsToken = tsa.GetTimeStampToken(tsImprint);
            }
            catch (Exception e) {
                throw new GeneralSecurityException(e.Message, e);
            }
            if (contentEstimated + 2 < tsToken.Length)
            {
                throw new System.IO.IOException("Not enough space");
            }
            byte[] paddedSig = new byte[contentEstimated];
            System.Array.Copy(tsToken, 0, paddedSig, 0, tsToken.Length);
            PdfDictionary dic2 = new PdfDictionary();

            dic2.Put(PdfName.Contents, new PdfString(paddedSig).SetHexWriting(true));
            Close(dic2);
            closed = true;
        }
Esempio n. 20
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();
            }
        }
Esempio n. 21
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();
                }
            }
        }
Esempio n. 22
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();
                }
            }
        }
Esempio n. 23
0
        public byte[] LTVEnable(byte[] pdf, ITSAClient tsaClient)
        {
            PdfReader    document      = new PdfReader(pdf);
            MemoryStream stream        = new MemoryStream();
            string       signatureName = "";

            PdfStamper pdfStamper = new PdfStamper(document, stream, '0', true);
            //PdfStamper pdfStamper = PdfStamper.CreateSignature(document, stream, '\0');
            AcroFields    fields      = pdfStamper.AcroFields;
            List <string> _fieldNames = fields.GetSignatureNames();

            foreach (string _fieldName in _fieldNames)
            {
                signatureName = _fieldName;
            }

            LtvVerification v     = pdfStamper.LtvVerification;
            PdfPKCS7        pkcs7 = fields.VerifySignature(signatureName);
            CrlClientOnline crl   = new CrlClientOnline(pkcs7.SignCertificateChain);

            if (pkcs7.IsTsp)
            {
                v.AddVerification(signatureName, null, crl,
                                  LtvVerification.CertificateOption.SIGNING_CERTIFICATE,
                                  LtvVerification.Level.CRL,
                                  LtvVerification.CertificateInclusion.NO);
            }
            else
            {
                v.AddVerification(signatureName, null, crl,
                                  LtvVerification.CertificateOption.WHOLE_CHAIN,
                                  LtvVerification.Level.CRL,
                                  LtvVerification.CertificateInclusion.NO);
            }
            pdfStamper.Close();
            //PdfSignatureAppearance sap = pdfStamper.SignatureAppearance;
            //LtvTimestamp.Timestamp(sap, tsaClient, null);

            return(stream.ToArray());
        }
Esempio n. 24
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);
        }
Esempio n. 25
0
        /**
         * Signs a document with a PAdES-LTV Timestamp. The document is closed at the end.
         * @param sap the signature appearance
         * @param tsa the timestamp generator
         * @param signatureName the signature name or null to have a name generated
         * automatically
         * @throws Exception
         */
        public static void Timestamp(PdfSignatureAppearance sap, ITSAClient tsa, String signatureName) {
            int contentEstimated = tsa.GetTokenSizeEstimate();
            sap.AddDeveloperExtension(PdfDeveloperExtension.ESIC_1_7_EXTENSIONLEVEL5);
            sap.SetVisibleSignature(new Rectangle(0,0,0,0), 1, signatureName);

            PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ETSI_RFC3161);
            dic.Put(PdfName.TYPE, PdfName.DOCTIMESTAMP);
            sap.CryptoDictionary = dic;

            Dictionary<PdfName,int> exc = new Dictionary<PdfName,int>();
            exc[PdfName.CONTENTS] = contentEstimated * 2 + 2;
            sap.PreClose(exc);
            Stream data = sap.GetRangeStream();
            IDigest messageDigest = tsa.GetMessageDigest();
            byte[] buf = new byte[4096];
            int n;
            while ((n = data.Read(buf, 0, buf.Length)) > 0) {
                messageDigest.BlockUpdate(buf, 0, n);
            }
            byte[] tsImprint = new byte[messageDigest.GetDigestSize()];
            messageDigest.DoFinal(tsImprint, 0);
            byte[] tsToken;
            try {
        	    tsToken = tsa.GetTimeStampToken(tsImprint);
            }
            catch(Exception e) {
        	    throw new GeneralSecurityException(e.Message);
            }
            //TODO jbonilla Validar para el TSA de Certificado que devuelve un valor muy grande.
            if (contentEstimated + 2 < tsToken.Length)
                throw new IOException("Not enough space");

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

            PdfDictionary dic2 = new PdfDictionary();
            dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true));
            sap.Close(dic2);
        }
Esempio n. 26
0
        private static void DoSignPdfFile(PdfStamper stamper, ConversionProfile profile, JobPasswords jobPasswords)
        {
            var signing = profile.PdfSettings.Signature;

            if (!signing.Enabled) //Leave without signing
            {
                return;
            }

            Logger.Debug("Start signing file.");

            signing.CertificateFile = Path.GetFullPath(signing.CertificateFile);

            if (string.IsNullOrEmpty(jobPasswords.PdfSignaturePassword))
            {
                Logger.Error("Launched signing without certification password.");
                throw new ProcessingException("Launched signing without certification password.", 12204);
            }

            if (IsValidCertificatePassword(signing.CertificateFile, jobPasswords.PdfSignaturePassword) == false)
            {
                Logger.Error("Canceled signing. The password for certificate '" + signing.CertificateFile +
                             "' is wrong.");
                throw new ProcessingException(
                          "Canceled signing. The password for certificate '" + signing.CertificateFile + "' is wrong.",
                          12200);
            }

            if (CertificateHasPrivateKey(signing.CertificateFile, jobPasswords.PdfSignaturePassword) == false)
            {
                Logger.Error("Canceled signing. The certificate '" + signing.CertificateFile + "' has no private key.");
                throw new ProcessingException(
                          "Canceled signing. The certificate '" + signing.CertificateFile + "' has no private key.", 12201);
            }

            var    fsCert = new FileStream(signing.CertificateFile, FileMode.Open);
            var    ks     = new Pkcs12Store(fsCert, jobPasswords.PdfSignaturePassword.ToCharArray());
            string alias  = null;

            foreach (string al in ks.Aliases)
            {
                if (ks.IsKeyEntry(al) && ks.GetKey(al).Key.IsPrivate)
                {
                    alias = al;
                    break;
                }
            }

            fsCert.Close();
            ICipherParameters pk = ks.GetKey(alias).Key;
            var x     = ks.GetCertificateChain(alias);
            var chain = new X509Certificate[x.Length];

            for (var k = 0; k < x.Length; ++k)
            {
                chain[k] = x[k].Certificate;
            }

            ITSAClient tsc = null;

            if (!string.IsNullOrEmpty(signing.TimeServerUrl.Trim()))
            {
                if (!signing.TimeServerIsSecured)
                {
                    tsc = new TSAClientBouncyCastle(signing.TimeServerUrl);
                }
                else
                {
                    tsc = new TSAClientBouncyCastle(signing.TimeServerUrl, signing.TimeServerLoginName,
                                                    signing.TimeServerPassword);
                }
            }

            var psa = stamper.SignatureAppearance;

            if (tsc == null)
            {
                psa.SetCrypto(pk, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
            }
            else
            {
                psa.SetCrypto(null, chain, null, PdfSignatureAppearance.SELF_SIGNED);
            }

            if (!profile.PdfSettings.Signature.AllowMultiSigning)
            {
                //Lock PDF, except for annotations and form filling (irrelevant for clawPDF)
                psa.CertificationLevel = PdfSignatureAppearance.CERTIFIED_FORM_FILLING_AND_ANNOTATIONS;
            }

            psa.Reason   = signing.SignReason;
            psa.Contact  = signing.SignContact;
            psa.Location = signing.SignLocation;

            if (signing.DisplaySignatureInDocument)
            {
                var signPage = SignPageNr(stamper, signing);

                psa.SetVisibleSignature(new Rectangle(signing.LeftX, signing.LeftY, signing.RightX, signing.RightY),
                                        signPage, null);
            }

            var dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached"));

            dic.Reason           = psa.Reason;
            dic.Location         = psa.Location;
            dic.Contact          = psa.Contact;
            dic.Date             = new PdfDate(psa.SignDate);
            psa.CryptoDictionary = dic;

            const int contentEstimated = 15000;
            // Preallocate excluded byte-range for the signature content (hex encoded)
            var exc = new Dictionary <PdfName, int>();

            exc[PdfName.CONTENTS] = contentEstimated * 2 + 2;
            psa.PreClose(exc);
            const string hashAlgorithm = "SHA1"; //Always use HashAlgorithm "SHA1"
            var          sgn           = new PdfPKCS7(pk, chain, null, hashAlgorithm, false);
            var          messageDigest = DigestUtilities.GetDigest(hashAlgorithm);
            var          data          = psa.GetRangeStream();
            var          buf           = new byte[8192];
            int          n;

            while ((n = data.Read(buf, 0, buf.Length)) > 0)
            {
                messageDigest.BlockUpdate(buf, 0, n);
            }
            var hash = new byte[messageDigest.GetDigestSize()];

            messageDigest.DoFinal(hash, 0);
            byte[] ocsp = null;
            if (chain.Length >= 2)
            {
                var url = PdfPKCS7.GetOCSPURL(chain[0]);
                if (!string.IsNullOrEmpty(url))
                {
                    ocsp = new OcspClientBouncyCastle().GetEncoded(chain[0], chain[1], url);
                }
            }

            var cal = psa.SignDate;
            var sh  = sgn.GetAuthenticatedAttributeBytes(hash, cal, ocsp);

            sgn.Update(sh, 0, sh.Length);

            var paddedSig = new byte[contentEstimated];

            if (tsc != null)
            {
                byte[] encodedSigTsa = null;
                try
                {
                    encodedSigTsa = sgn.GetEncodedPKCS7(hash, cal, tsc, ocsp);
                    Array.Copy(encodedSigTsa, 0, paddedSig, 0, encodedSigTsa.Length);
                }
                catch (Exception ex)
                {
                    throw new ProcessingException(
                              ex.GetType() + " while connecting to timeserver (can't connect to timeserver): " + ex.Message,
                              12205);
                }

                if (contentEstimated + 2 < encodedSigTsa.Length)
                {
                    throw new ProcessingException(
                              "Not enough space for signature", 12202);
                }
            }
            else
            {
                var encodedSig = sgn.GetEncodedPKCS7(hash, cal);
                Array.Copy(encodedSig, 0, paddedSig, 0, encodedSig.Length);
                if (contentEstimated + 2 < encodedSig.Length)
                {
                    throw new ProcessingException("Not enough space for signature", 12203);
                }
            }

            var dic2 = new PdfDictionary();

            dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true));
            psa.Close(dic2);
        }
Esempio n. 27
0
        /**
        * Gets the bytes for the PKCS7SignedData object. Optionally the authenticatedAttributes
        * in the signerInfo can also be set, OR a time-stamp-authority client
        * may be provided.
        * @param secondDigest the digest in the authenticatedAttributes
        * @param signingTime the signing time in the authenticatedAttributes
        * @param tsaClient TSAClient - null or an optional time stamp authority client
        * @return byte[] the bytes for the PKCS7SignedData object
        * @since   2.1.6
        */
        public byte[] GetEncodedPKCS7(byte[] secondDigest, DateTime signingTime, ITSAClient tsaClient, byte[] ocsp) {
            if (externalDigest != null) {
                digest = externalDigest;
                if (RSAdata != null)
                    RSAdata = externalRSAdata;
            }
            else if (externalRSAdata != null && RSAdata != null) {
                RSAdata = externalRSAdata;
                sig.BlockUpdate(RSAdata, 0, RSAdata.Length);
                digest = sig.GenerateSignature();
            }
            else {
                if (RSAdata != null) {
                    RSAdata = new byte[messageDigest.GetDigestSize()];
                    messageDigest.DoFinal(RSAdata, 0);
                    sig.BlockUpdate(RSAdata, 0, RSAdata.Length);
                }
                digest = sig.GenerateSignature();
            }
            
            // Create the set of Hash algorithms
            Asn1EncodableVector digestAlgorithms = new Asn1EncodableVector();
            foreach (string dal in digestalgos.Keys) {
                Asn1EncodableVector algos = new Asn1EncodableVector();
                algos.Add(new DerObjectIdentifier(dal));
                algos.Add(DerNull.Instance);
                digestAlgorithms.Add(new DerSequence(algos));
            }
            
            // Create the contentInfo.
            Asn1EncodableVector v = new Asn1EncodableVector();
            v.Add(new DerObjectIdentifier(ID_PKCS7_DATA));
            if (RSAdata != null)
                v.Add(new DerTaggedObject(0, new DerOctetString(RSAdata)));
            DerSequence contentinfo = new DerSequence(v);
            
            // Get all the certificates
            //
            v = new Asn1EncodableVector();
            foreach (X509Certificate xcert in certs) {
                Asn1InputStream tempstream = new Asn1InputStream(new MemoryStream(xcert.GetEncoded()));
                v.Add(tempstream.ReadObject());
            }
            
            DerSet dercertificates = new DerSet(v);
            
            // Create signerinfo structure.
            //
            Asn1EncodableVector signerinfo = new Asn1EncodableVector();
            
            // Add the signerInfo version
            //
            signerinfo.Add(new DerInteger(signerversion));
            
            v = new Asn1EncodableVector();
            v.Add(GetIssuer(signCert.GetTbsCertificate()));
            v.Add(new DerInteger(signCert.SerialNumber));
            signerinfo.Add(new DerSequence(v));
            
            // Add the digestAlgorithm
            v = new Asn1EncodableVector();
            v.Add(new DerObjectIdentifier(digestAlgorithm));
            v.Add(DerNull.Instance);
            signerinfo.Add(new DerSequence(v));
            
            // add the authenticated attribute if present
            if (secondDigest != null /*&& signingTime != null*/) {
                signerinfo.Add(new DerTaggedObject(false, 0, GetAuthenticatedAttributeSet(secondDigest, signingTime, ocsp)));
            }
            // Add the digestEncryptionAlgorithm
            v = new Asn1EncodableVector();
            v.Add(new DerObjectIdentifier(digestEncryptionAlgorithm));
            v.Add(DerNull.Instance);
            signerinfo.Add(new DerSequence(v));
            
            // Add the digest
            signerinfo.Add(new DerOctetString(digest));
            
            // When requested, go get and add the timestamp. May throw an exception.
            // Added by Martin Brunecky, 07/12/2007 folowing Aiken Sam, 2006-11-15
            // Sam found Adobe expects time-stamped SHA1-1 of the encrypted digest
            if (tsaClient != null) {
                byte[] tsImprint = new System.Security.Cryptography.SHA1CryptoServiceProvider().ComputeHash(digest);
                byte[] tsToken = tsaClient.GetTimeStampToken(this, tsImprint);
                if (tsToken != null) {
                    Asn1EncodableVector unauthAttributes = BuildUnauthenticatedAttributes(tsToken);
                    if (unauthAttributes != null) {
                        signerinfo.Add(new DerTaggedObject(false, 1, new DerSet(unauthAttributes)));
                    }
                }
            }
            
            // Finally build the body out of all the components above
            Asn1EncodableVector body = new Asn1EncodableVector();
            body.Add(new DerInteger(version));
            body.Add(new DerSet(digestAlgorithms));
            body.Add(contentinfo);
            body.Add(new DerTaggedObject(false, 0, dercertificates));
            
//                if (crls.Count > 0) {
//                    v = new Asn1EncodableVector();
//                    for (Iterator i = crls.Iterator();i.HasNext();) {
//                        Asn1InputStream t = new Asn1InputStream(new ByteArrayInputStream((((X509CRL)i.Next()).GetEncoded())));
//                        v.Add(t.ReadObject());
//                    }
//                    DERSet dercrls = new DERSet(v);
//                    body.Add(new DERTaggedObject(false, 1, dercrls));
//                }
            
            // Only allow one signerInfo
            body.Add(new DerSet(new DerSequence(signerinfo)));
            
            // Now we have the body, wrap it in it's PKCS7Signed shell
            // and return it
            //
            Asn1EncodableVector whole = new Asn1EncodableVector();
            whole.Add(new DerObjectIdentifier(ID_PKCS7_SIGNED_DATA));
            whole.Add(new DerTaggedObject(0, new DerSequence(body)));
            
            MemoryStream bOut = new MemoryStream();
            
            Asn1OutputStream dout = new Asn1OutputStream(bOut);
            dout.WriteObject(new DerSequence(whole));
            dout.Close();
            
            return bOut.ToArray();
        }
Esempio n. 28
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);
 }
Esempio n. 29
0
        /**
         * Gets the bytes for the PKCS7SignedData object. Optionally the authenticatedAttributes
         * in the signerInfo can also be set, OR a time-stamp-authority client
         * may be provided.
         * @param secondDigest the digest in the authenticatedAttributes
         * @param signingTime the signing time in the authenticatedAttributes
         * @param tsaClient TSAClient - null or an optional time stamp authority client
         * @return byte[] the bytes for the PKCS7SignedData object
         * @since   2.1.6
         */
        public byte[] GetEncodedPKCS7(byte[] secondDigest, DateTime signingTime, ITSAClient tsaClient, byte[] ocsp, ICollection <byte[]> crlBytes, CryptoStandard sigtype)
        {
            if (externalDigest != null)
            {
                digest = externalDigest;
                if (RSAdata != null)
                {
                    RSAdata = externalRSAdata;
                }
            }
            else if (externalRSAdata != null && RSAdata != null)
            {
                RSAdata = externalRSAdata;
                sig.BlockUpdate(RSAdata, 0, RSAdata.Length);
                digest = sig.GenerateSignature();
            }
            else
            {
                if (RSAdata != null)
                {
                    RSAdata = new byte[messageDigest.GetDigestSize()];
                    messageDigest.DoFinal(RSAdata, 0);
                    sig.BlockUpdate(RSAdata, 0, RSAdata.Length);
                }
                digest = sig.GenerateSignature();
            }

            // Create the set of Hash algorithms
            Asn1EncodableVector digestAlgorithms = new Asn1EncodableVector();

            foreach (string dal in digestalgos.Keys)
            {
                Asn1EncodableVector algos = new Asn1EncodableVector();
                algos.Add(new DerObjectIdentifier(dal));
                algos.Add(DerNull.Instance);
                digestAlgorithms.Add(new DerSequence(algos));
            }

            // Create the contentInfo.
            Asn1EncodableVector v = new Asn1EncodableVector();

            v.Add(new DerObjectIdentifier(SecurityIDs.ID_PKCS7_DATA));
            if (RSAdata != null)
            {
                v.Add(new DerTaggedObject(0, new DerOctetString(RSAdata)));
            }
            DerSequence contentinfo = new DerSequence(v);

            // Get all the certificates
            //
            v = new Asn1EncodableVector();
            foreach (X509Certificate xcert in certs)
            {
                Asn1InputStream tempstream = new Asn1InputStream(new MemoryStream(xcert.GetEncoded()));
                v.Add(tempstream.ReadObject());
            }

            DerSet dercertificates = new DerSet(v);

            // Create signerinfo structure.
            //
            Asn1EncodableVector signerinfo = new Asn1EncodableVector();

            // Add the signerInfo version
            //
            signerinfo.Add(new DerInteger(signerversion));

            v = new Asn1EncodableVector();
            v.Add(CertificateInfo.GetIssuer(signCert.GetTbsCertificate()));
            v.Add(new DerInteger(signCert.SerialNumber));
            signerinfo.Add(new DerSequence(v));

            // Add the digestAlgorithm
            v = new Asn1EncodableVector();
            v.Add(new DerObjectIdentifier(digestAlgorithmOid));
            v.Add(DerNull.Instance);
            signerinfo.Add(new DerSequence(v));

            // add the authenticated attribute if present
            if (secondDigest != null /*&& signingTime != null*/)
            {
                signerinfo.Add(new DerTaggedObject(false, 0, GetAuthenticatedAttributeSet(secondDigest, signingTime, ocsp, crlBytes, sigtype)));
            }
            // Add the digestEncryptionAlgorithm
            v = new Asn1EncodableVector();
            v.Add(new DerObjectIdentifier(digestEncryptionAlgorithmOid));
            v.Add(DerNull.Instance);
            signerinfo.Add(new DerSequence(v));

            // Add the digest
            signerinfo.Add(new DerOctetString(digest));

            // When requested, go get and add the timestamp. May throw an exception.
            // Added by Martin Brunecky, 07/12/2007 folowing Aiken Sam, 2006-11-15
            // Sam found Adobe expects time-stamped SHA1-1 of the encrypted digest
            if (tsaClient != null)
            {
                byte[] tsImprint = DigestAlgorithms.Digest(tsaClient.GetMessageDigest(), digest);
                byte[] tsToken   = tsaClient.GetTimeStampToken(tsImprint);
                if (tsToken != null)
                {
                    Asn1EncodableVector unauthAttributes = BuildUnauthenticatedAttributes(tsToken);
                    if (unauthAttributes != null)
                    {
                        signerinfo.Add(new DerTaggedObject(false, 1, new DerSet(unauthAttributes)));
                    }
                }
            }

            // Finally build the body out of all the components above
            Asn1EncodableVector body = new Asn1EncodableVector();

            body.Add(new DerInteger(version));
            body.Add(new DerSet(digestAlgorithms));
            body.Add(contentinfo);
            body.Add(new DerTaggedObject(false, 0, dercertificates));

            // Only allow one signerInfo
            body.Add(new DerSet(new DerSequence(signerinfo)));

            // Now we have the body, wrap it in it's PKCS7Signed shell
            // and return it
            //
            Asn1EncodableVector whole = new Asn1EncodableVector();

            whole.Add(new DerObjectIdentifier(SecurityIDs.ID_PKCS7_SIGNED_DATA));
            whole.Add(new DerTaggedObject(0, new DerSequence(body)));

            MemoryStream bOut = new MemoryStream();

            Asn1OutputStream dout = new Asn1OutputStream(bOut);

            dout.WriteObject(new DerSequence(whole));
            dout.Close();

            return(bOut.ToArray());
        }
Esempio n. 30
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;
        }
Esempio n. 31
0
        public byte[] signPdf(byte[] inputPdf, byte[] sigImg, string signatureField)
        {
            this.getCRLList();
            Console.WriteLine("Read PDF");
            PdfReader    reader = new PdfReader(inputPdf);
            MemoryStream output = new MemoryStream();

            PdfStamper stamper = PdfStamper.CreateSignature(reader, output, '\0', null, true);

            PdfSignatureAppearance sap = stamper.SignatureAppearance;

            sap.Reason   = "test";
            sap.Location = "Bangkok";
            // Set Signature Image
            if (sigImg != null)
            {
                sap.SignatureGraphic       = Image.GetInstance(sigImg);
                sap.ImageScale             = -1;
                sap.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC;
            }
            // Set Signature Field
            if (signatureField.Equals("") || signatureField == null)
            {
                Rectangle location = new Rectangle(10, 10, 300, 100);
                sap.SetVisibleSignature(location, 1, "signatureField");
            }
            else
            {
                sap.SetVisibleSignature(signatureField);
            }

            sap.CertificationLevel = PdfSignatureAppearance.NOT_CERTIFIED;

            //Create TSA server
            ITSAClient tsaClient      = null;
            Boolean    isTsaConnected = false;

            if (tsa)
            {
                tsaClient = new TSAClientBouncyCastle(tsaUrl, tsaUsername, tsaPassword);
                for (int retry = 0; retry < 5; retry++)
                {
                    try
                    {
                        //int hash = tsaClient.GetHashCode();
                        string testString = "test";
                        byte[] digest;
                        using (SHA256Managed sha256 = new SHA256Managed())
                        {
                            digest = sha256.ComputeHash(Encoding.UTF8.GetBytes(testString));
                        }
                        tsaClient.GetTimeStampToken(digest);
                        isTsaConnected = true;
                        break;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.StackTrace);
                    }
                    Console.WriteLine("retry " + (retry + 1));
                }
            }
            //Do Signing Check not null timestamp and crl
            if (tsaClient != null && crlList != null && isTsaConnected)
            {
                try
                {
                    MakeSignature.SignDetached(sap, this.signature, chain, this.crlList, null, tsaClient, 0, CryptoStandard.CADES);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.StackTrace);
                }
            }
            else
            {
                Console.WriteLine("Cannot sign the PDF file.");
                return(null);
            }
            reader.Close();
            stamper.Close();
            signature = null;


            return(output.ToArray());
        }
Esempio n. 32
0
 public HomeController(ITSAClient airportClient, IAirportCodeClient airportCodeClient)
 {
     _airportClient     = airportClient;
     _airportCodeClient = airportCodeClient;
 }
        /**
         * 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));
        }
        /// <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();
            }
        }
 public void SetTsaClient(string url, string user, string password)
 {
     TsaClient = new TSAClientBouncyCastle(url, user, password);
 }
    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();
            }
        }
    }
Esempio n. 38
0
        private ActionResult SignPdfFile(PdfStamper stamper, IJob job)
        {
            Signing s = job.Profile.PdfSettings.Signing;

            //Leave without signing //WEG!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            if (!s.Enable)
            {
                if (stamper != null)
                {
                    stamper.Close();
                    return(new ActionResult());
                }

                Logger.Error("Could not create Stamper for Encryption, without Signing");
                return(new ActionResult(ActionId, 104));
            }

            //Continue for Signing
            s.CertificationFile = Path.GetFullPath(s.CertificationFile);

            if (IsValidCertificatePassword(s.CertificationFile, job.Passwords.PdfSignaturePassword) == false)
            {
                Logger.Error("Canceled signing. The password for certificate '" + s.CertificationFile + "' is wrong.");
                stamper.Close();
                return(new ActionResult(ActionId, 105));
            }
            if (CertificateHasPrivateKey(s.CertificationFile, job.Passwords.PdfSignaturePassword) == false)
            {
                Logger.Error("Canceled signing. The certificate '" + s.CertificationFile + "' has no private key.");
                stamper.Close();
                return(new ActionResult(ActionId, 106));
            }

            var    fsCert = new FileStream(s.CertificationFile, FileMode.Open);
            var    ks     = new Pkcs12Store(fsCert, job.Passwords.PdfSignaturePassword.ToCharArray());
            string alias  = null;

            foreach (string al in ks.Aliases)
            {
                if (ks.IsKeyEntry(al) && ks.GetKey(al).Key.IsPrivate)
                {
                    alias = al;
                    break;
                }
            }
            fsCert.Close();
            ICipherParameters pk = ks.GetKey(alias).Key;

            X509CertificateEntry[] x = ks.GetCertificateChain(alias);
            var chain = new X509Certificate[x.Length];

            for (int k = 0; k < x.Length; ++k)
            {
                chain[k] = x[k].Certificate;
            }

            ITSAClient tsc = null;

            if (s.TimeServerUrl.Trim() != "") //Timeserver with LogIn?
            {
                tsc = new TSAClientBouncyCastle(s.TimeServerUrl /*, TimeServerLogonName, TimeServerLogonPassword*/);
            }

            PdfSignatureAppearance sap = stamper.SignatureAppearance;

            if (tsc == null)
            {
                sap.SetCrypto(pk, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
            }
            else
            {
                sap.SetCrypto(null, chain, null, PdfSignatureAppearance.SELF_SIGNED);
            }

            sap.Reason   = s.SignReason;
            sap.Contact  = s.SignContact;
            sap.Location = s.SignLocation;

            if (s.DisplaySignatureInPdf)
            {
                int signPage = SignPageNr(job);
                sap.SetVisibleSignature(new Rectangle(s.LeftX, s.LeftY, s.RightX, s.RightY),
                                        signPage, null);
            }

            var dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached"));

            dic.Reason           = sap.Reason;
            dic.Location         = sap.Location;
            dic.Contact          = sap.Contact;
            dic.Date             = new PdfDate(sap.SignDate);
            sap.CryptoDictionary = dic;

            const int contentEstimated = 15000;
            // Preallocate excluded byte-range for the signature content (hex encoded)
            var exc = new Dictionary <PdfName, int>();

            exc[PdfName.CONTENTS] = contentEstimated * 2 + 2;
            sap.PreClose(exc);
            const string hashAlgorithm = "SHA1"; //Always use HashAlgorithm "SHA1"
            var          sgn           = new PdfPKCS7(pk, chain, null, hashAlgorithm, false);
            IDigest      messageDigest = DigestUtilities.GetDigest(hashAlgorithm);
            Stream       data          = sap.GetRangeStream();
            var          buf           = new byte[8192];
            int          n;

            while ((n = data.Read(buf, 0, buf.Length)) > 0)
            {
                messageDigest.BlockUpdate(buf, 0, n);
            }
            var hash = new byte[messageDigest.GetDigestSize()];

            messageDigest.DoFinal(hash, 0);
            byte[] ocsp = null;
            if (chain.Length >= 2)
            {
                String url = PdfPKCS7.GetOCSPURL(chain[0]);
                if (!string.IsNullOrEmpty(url))
                {
                    ocsp = new OcspClientBouncyCastle().GetEncoded(chain[0], chain[1], url);
                }
            }
            DateTime cal = sap.SignDate;

            byte[] sh = sgn.GetAuthenticatedAttributeBytes(hash, cal, ocsp);
            sgn.Update(sh, 0, sh.Length);

            var paddedSig = new byte[contentEstimated];

            if (tsc != null)
            {
                byte[] encodedSigTsa = sgn.GetEncodedPKCS7(hash, cal, tsc, ocsp);
                Array.Copy(encodedSigTsa, 0, paddedSig, 0, encodedSigTsa.Length);
                if (contentEstimated + 2 < encodedSigTsa.Length)
                {
                    Logger.Error("Not enough space for signature");
                    return(new ActionResult(ActionId, 107));
                }
            }
            else
            {
                byte[] encodedSig = sgn.GetEncodedPKCS7(hash, cal);
                Array.Copy(encodedSig, 0, paddedSig, 0, encodedSig.Length);
                if (contentEstimated + 2 < encodedSig.Length)
                {
                    Logger.Error("Not enough space for signature");
                    return(new ActionResult(ActionId, 107));
                }
            }

            var dic2 = new PdfDictionary();

            dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true));
            sap.Close(dic2);

            return(new ActionResult());
        }