Beispiel #1
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();
        }
        public static async Task SignPdfFile(String accessToken, String credentialId, String pin, String otp, String inPath, String outPath)
        {
            try
            {
                PdfReader reader = new PdfReader(inPath);
                PdfSigner signer = new PdfSigner(reader, new FileStream(outPath, FileMode.Create), new StampingProperties());

                PdfSignatureAppearance appearance = signer.GetSignatureAppearance()
                                                    .SetReason("Test semnatura digitala")
                                                    .SetLocation("Bucuresti, RO")

                                                    .SetReuseAppearance(false);
                Rectangle rect = new Rectangle(300, 690, 200, 100);
                appearance.SetPageRect(rect).SetPageNumber(1);
                signer.SetFieldName("semnatura iText7");

                IExternalSignature pks = new CSCPAdESSignature(accessToken, credentialId, pin, otp);

                X509Certificate[] chain = await CSC_API_Utils.GetCertChainAsync(accessToken, credentialId);

                ICrlClient signingCertCrl = new CrlClientOnline(chain);

                List <ICrlClient> crlList = new List <ICrlClient>();
                crlList.Add(signingCertCrl);
                ITSAClient tsaClient = new TSAClientBouncyCastle("http://timestamp.globalsign.com/scripts/timestamp.dll");


                signer.SignDetached(pks, chain, crlList, null, tsaClient, 0, PdfSigner.CryptoStandard.CADES);
            }
            catch (Exception e)
            {
                logger.Error(e.Message);
            }
        }
Beispiel #3
0
        private void addTsa(PdfSignatureAppearance signAppearance)
        {
            var es  = new PrivateKeySignature(_asymmetricKeyParameter, "SHA-256");
            var tsc = new TSAClientBouncyCastle(SignatureData.TsaClient.Url, SignatureData.TsaClient.UserName, SignatureData.TsaClient.Password);

            MakeSignature.SignDetached(signAppearance, es, _chain, null, null, tsc, 0, CryptoStandard.CMS);
        }
Beispiel #4
0
        void Button4Click(object sender, EventArgs e)
        {
            if (!tsaCbx.Checked || TSAUrlTextBox.Text == "")
            {
                MessageBox.Show("Marca temporale non selezionata, oppure server non definito");
                return;
            }

            string TSA_URL   = TSAUrlTextBox.Text;
            string TSA_ACCNT = tsaLogin.Text;
            string TSA_PASSW = tsaPwd.Text;

            if (fbd.ShowDialog() == DialogResult.OK)
            {
                string   foldername = fbd.SelectedPath;
                string[] files      = Directory.GetFiles(foldername, "*.pdf");
                pb.Minimum = 0;
                pb.Maximum = files.Length;
                pb.Visible = true;
                lb2.Items.Clear();
                foreach (string s in files)
                {
                    //just filename
                    try {
                        string ext = s.Substring(1 + s.LastIndexOf(@".")).ToLowerInvariant();
                        if (ext == "pdf" || ext == "PDF")
                        {
                            //ricreo il percorso con il nome del nuovo file
                            string          file      = s.Substring(1 + s.LastIndexOf(@"\"));
                            string          NuovoFile = s.Substring(0, s.LastIndexOf(@"\") + 1) + file.Substring(0, file.LastIndexOf(".")) + "_validato_" + DateTime.Now.ToFileTime() + ".pdf";
                            PdfReader       r         = new PdfReader(s);
                            FileStream      fout      = new FileStream(NuovoFile, FileMode.Create);
                            PdfStamper      stp       = PdfStamper.CreateSignature(r, fout, '\0', null, true);
                            LtvVerification v         = stp.LtvVerification;
                            AcroFields      af        = stp.AcroFields;
                            foreach (string sigName in af.GetSignatureNames())
                            {
                                v.AddVerification(sigName, new OcspClientBouncyCastle(), new CrlClientImp(), LtvVerification.CertificateOption.WHOLE_CHAIN, LtvVerification.Level.OCSP_CRL, LtvVerification.CertificateInclusion.NO);
                            }
                            PdfSignatureAppearance sap = stp.SignatureAppearance;
                            TSAClientBouncyCastle  tsa = new TSAClientBouncyCastle(TSA_URL, TSA_ACCNT, TSA_PASSW, 6500, "sha256");
                            LtvTimestamp.Timestamp(sap, tsa, null);
                            lb2.Items.Add(NuovoFile);
                            lb2.Refresh();
                            pb.Increment(1);
                        }
                    }
                    catch (Exception ex) {
                        MessageBox.Show(ex.ToString());
                        pb.Visible = false;
                        return;
                    }
                }
                MessageBox.Show(pb.Maximum.ToString() + " file firmati correttamente", "Operazione Completata");
                pb.Visible = false;
            }
        }
Beispiel #5
0
        public static void Main(String[] args)
        {
            Properties properties = new Properties();

            properties.Load(new FileStream("c:/home/blowagie/key.properties", FileMode.Open));
            String path = properties["PRIVATE"];

            char[] pass    = properties["PASSWORD"].ToCharArray();
            String tsaUrl  = properties["TSAURL"];
            String tsaUser = properties["TSAUSERNAME"];
            String tsaPass = properties["TSAPASSWORD"];

            Pkcs12Store ks = new Pkcs12Store();

            ks.Load(new FileStream(path, FileMode.Open), pass);
            String alias = "";

            foreach (string al in ks.Aliases)
            {
                if (ks.IsKeyEntry(al) && ks.GetKey(al).Key.IsPrivate)
                {
                    alias = al;
                    break;
                }
            }
            AsymmetricKeyParameter  pk    = ks.GetKey(alias).Key;
            IList <X509Certificate> chain = new List <X509Certificate>();

            foreach (X509CertificateEntry entry in ks.GetCertificateChain(alias))
            {
                chain.Add(entry.Certificate);
            }
            IOcspClient           ocspClient = new OcspClientBouncyCastle();
            TSAClientBouncyCastle tsaClient  = new TSAClientBouncyCastle(tsaUrl, tsaUser, tsaPass);

            C3_12_SignWithEstimatedSize app = new C3_12_SignWithEstimatedSize();
            bool succeeded     = false;
            int  estimatedSize = 10300;

            while (!succeeded)
            {
                try {
                    Console.WriteLine("Attempt: " + estimatedSize + " bytes");
                    C3_01_SignWithCAcert.Sign(DEST, chain, pk, DigestAlgorithms.SHA256, CryptoStandard.CMS, "Test", "Ghent",
                                              null, ocspClient, tsaClient, estimatedSize);
                    succeeded = true;
                    Console.WriteLine("Succeeded!");
                }
                catch (IOException ioe) {
                    Console.WriteLine("Not succeeded: " + ioe.Message);
                    estimatedSize += 50;
                }
            }
            Console.ReadKey();
        }
Beispiel #6
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);
        }
        public static void Main(String[] args)
        {
            DirectoryInfo directory = new DirectoryInfo(DEST);

            directory.Create();

            Properties properties = new Properties();

            // Specify the correct path to the certificate
            properties.Load(new FileStream("c:/home/blowagie/key.properties", FileMode.Open, FileAccess.Read));
            String path = properties.GetProperty("PRIVATE");

            char[] pass    = properties.GetProperty("PASSWORD").ToCharArray();
            String tsaUrl  = properties.GetProperty("TSAURL");
            String tsaUser = properties.GetProperty("TSAUSERNAME");
            String tsaPass = properties.GetProperty("TSAPASSWORD");

            Pkcs12Store pk12  = new Pkcs12Store(new FileStream(path, FileMode.Open, FileAccess.Read), pass);
            string      alias = null;

            foreach (var a in pk12.Aliases)
            {
                alias = ((string)a);
                if (pk12.IsKeyEntry(alias))
                {
                    break;
                }
            }

            ICipherParameters pk = pk12.GetKey(alias).Key;

            X509CertificateEntry[] ce    = pk12.GetCertificateChain(alias);
            X509Certificate[]      chain = new X509Certificate[ce.Length];
            for (int k = 0; k < ce.Length; ++k)
            {
                chain[k] = ce[k].Certificate;
            }

            IOcspClient ocspClient = new OcspClientBouncyCastle(null);

            /* Create an instance of TSAClientBouncyCastle, an implementation of TSAClient.
             * Pass the timestamp authority server url.
             * Note that not all TSA would require user credentials.
             */
            ITSAClient tsaClient = new TSAClientBouncyCastle(tsaUrl, tsaUser, tsaPass);

            new C3_09_SignWithTSA().Sign(SRC, DEST + RESULT_FILES[0], chain, pk,
                                         DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS,
                                         "Test", "Ghent", null, ocspClient, tsaClient, 0);
        }
Beispiel #8
0
        private static void LTVEnable()
        {
            DigitalSig dSig    = new DigitalSig();
            string     pdfPath = @"";

            byte[] pdf = File.ReadAllBytes(pdfPath);

            string     tsaUrl    = "";
            ITSAClient tsaClient = new TSAClientBouncyCastle(tsaUrl);

            byte[] result = dSig.LTVEnable(pdf, tsaClient);

            string outputPath = @"";

            File.WriteAllBytes(outputPath, result);
        }
Beispiel #9
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();
            }
        }
        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));
        }
Beispiel #11
0
        private void BtnTestaTimeStamp_Click(object sender, EventArgs e)
        {
            List <string> oListaServer = new List <string>();

            oListaServer.Add("https://freetsa.org/tsr");
            oListaServer.Add("http://timestamp.globalsign.com/scripts/timstamp.dll");
            //oListaServer.Add("https://timestamp.geotrust.com/tsa");
            oListaServer.Add("http://timestamp.comodoca.com/rfc3161");
            //oListaServer.Add("http://timestamp.wosign.com");
            oListaServer.Add("http://tsa.startssl.com/rfc3161");
            oListaServer.Add("http://time.certum.pl");
            oListaServer.Add("http://timestamp.digicert.com");
            //oListaServer.Add("http://dse200.ncipher.com/TSS/HttpTspServer");
            //oListaServer.Add("http://tsa.safecreative.org");
            oListaServer.Add("http://zeitstempel.dfn.de");
            oListaServer.Add("https://ca.signfiles.com/tsa/get.aspx");
            //oListaServer.Add("http://services.globaltrustfinder.com/adss/tsa");
            //oListaServer.Add("https://tsp.iaik.tugraz.at/tsp/TspRequest");
            oListaServer.Add("http://timestamp.apple.com/ts01");
            //oListaServer.Add("http://timestamp.entrust.net/TSS/RFC3161sha2TS");

            TSAClientBouncyCastle tsaClient = null;

            foreach (string URL in oListaServer)
            {
                try
                {
                    bool teste = TestaTimeStamp(URL);
                    if (teste)
                    {
                        MessageBox.Show("O servidor: " + URL + " respondeu o timestamp corretamente", ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("O servidor: " + URL + " não respondeu o timestamp corretamente", ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Um erro ocorreu ao tentar acessar o servidor: " + URL + ". Erro: " + getMSGErro(ex), ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Beispiel #12
0
        public static void Main(String[] args)
        {
            Properties properties = new Properties();

            properties.Load(new FileStream("c:/home/blowagie/key.properties", FileMode.Open));
            String path = properties["PRIVATE"];

            char[] pass    = properties["PASSWORD"].ToCharArray();
            String tsaUrl  = properties["TSAURL"];
            String tsaUser = properties["TSAUSERNAME"];
            String tsaPass = properties["TSAPASSWORD"];

            Pkcs12Store ks = new Pkcs12Store();

            ks.Load(new FileStream(path, FileMode.Open), pass);
            String alias = "";

            foreach (string al in ks.Aliases)
            {
                if (ks.IsKeyEntry(al) && ks.GetKey(al).Key.IsPrivate)
                {
                    alias = al;
                    break;
                }
            }
            AsymmetricKeyParameter  pk    = ks.GetKey(alias).Key;
            IList <X509Certificate> chain = new List <X509Certificate>();

            foreach (X509CertificateEntry entry in ks.GetCertificateChain(alias))
            {
                chain.Add(entry.Certificate);
            }
            IOcspClient           ocspClient = new OcspClientBouncyCastle();
            TSAClientBouncyCastle tsaClient  = new TSAClientBouncyCastle(tsaUrl, tsaUser, tsaPass);

            tsaClient.SetTSAInfo(new TSAInfoTimeStampLogger());
            C3_01_SignWithCAcert.Sign(DEST, chain, pk, DigestAlgorithms.SHA256, CryptoStandard.CMS, "Test",
                                      "Ghent",
                                      null, ocspClient, tsaClient, 0);
            Console.ReadKey();
        }
Beispiel #13
0
        public static void Main(String[] args)
        {
            LoggerFactory.GetInstance().SetLogger(new SysoLogger());
            Properties properties = new Properties();

            properties.Load(new FileStream("c:/home/blowagie/key.properties", FileMode.Open));
            String      tsaUrl  = properties["TSAURL"];
            String      tsaUser = properties["TSAUSERNAME"];
            String      tsaPass = properties["TSAPASSWORD"];
            C5_04_LTV   app     = new C5_04_LTV();
            ITSAClient  tsa     = new TSAClientBouncyCastle(tsaUrl, tsaUser, tsaPass, 6500, "SHA512");
            IOcspClient ocsp    = new OcspClientBouncyCastle();

            app.AddLtv(EXAMPLE1, String.Format(DEST, 1), ocsp, new CrlClientOnline(), tsa);
            Console.WriteLine();
            app.AddLtv(EXAMPLE2, String.Format(DEST, 2), ocsp, new CrlClientOnline(), tsa);
            Console.WriteLine();
            app.AddLtv(EXAMPLE3, String.Format(DEST, 3), ocsp, new CrlClientOnline(), tsa);
            Console.WriteLine();
            app.AddLtv(String.Format(DEST, 1), String.Format(DEST, 4), null, new CrlClientOnline(), tsa);
        }
Beispiel #14
0
        public static Org.BouncyCastle.Asn1.Asn1EncodableVector GetTimestamp(byte[] signature, string url, string user, string pass)
        {
            byte[] tsImprint = PdfEncryption.DigestComputeHash("SHA256", signature);

            int        size = 6500;
            ITSAClient tsc  = new TSAClientBouncyCastle(url, user, pass, size, "SHA256");
            String     ID_TIME_STAMP_TOKEN = "1.2.840.113549.1.9.16.2.14";         // RFC 3161 id-aa-timeStampToken

            Asn1InputStream tempstream = new Asn1InputStream(new MemoryStream(tsc.GetTimeStampToken(tsImprint)));

            Asn1EncodableVector unauthAttributes = new Asn1EncodableVector();

            Asn1EncodableVector v = new Asn1EncodableVector();

            v.Add(new DerObjectIdentifier(ID_TIME_STAMP_TOKEN));             // id-aa-timeStampToken
            Asn1Sequence seq = (Asn1Sequence)tempstream.ReadObject();

            v.Add(new DerSet(seq));

            unauthAttributes.Add(new DerSequence(v));
            return(unauthAttributes);
        }
Beispiel #15
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());
        }
Beispiel #16
0
 private void addTsa(PdfSignatureAppearance signAppearance)
 {
     var es = new PrivateKeySignature(_asymmetricKeyParameter, "SHA-256");
     var tsc = new TSAClientBouncyCastle(SignatureData.TsaClient.Url, SignatureData.TsaClient.UserName, SignatureData.TsaClient.Password);
     MakeSignature.SignDetached(signAppearance, es, _chain, null, null, tsc, 0, CryptoStandard.CMS);
 }
Beispiel #17
0
        static int Main(string[] args)
        {
            if (args.Length == 0)
            {
                PrintUsage();
                return((int)ExitCode.Success);
            }

            Arguments.Populate();

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

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

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

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

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

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


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

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

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

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

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

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

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

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

            return((int)ExitCode.Success);
        }
Beispiel #18
0
        private void btnSign_Click(object sender, EventArgs e)
        {
            try
            {
                // Set wait cursor
                this.Cursor = Cursors.WaitCursor;
                Application.DoEvents();

                X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                store.Open(OpenFlags.ReadOnly);

                // Get signature certificate for current citizen
                X509Certificate2Collection certsToShow = store.Certificates.Find(X509FindType.FindBySubjectName, "Assinatura", false);
                X509Certificate2Collection certs       = certsToShow.Find(X509FindType.FindBySubjectName, "BI" + txtIdNumber.Text, false);

                if (certs.Count <= 0)
                {
                    MessageBox.Show("Certificate not found.",
                                    "Error!",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Exclamation);
                    return;
                }

                var cert = certs[0];

                if (cert != null)
                {
                    // Sign every file found on listbox
                    foreach (string file in lbFilesToSign.Items)
                    {
                        try
                        {
                            // Get source folder and source filename
                            string sourceFolder = Path.GetDirectoryName(file);
                            string filename     = Path.GetFileName(file);

                            lblStatus.Text = "A assinar o file " + filename;

                            // Create "Signed" sub-folder if doesn't exists
                            string signedFolder = Path.Combine(sourceFolder, "Signed");

                            if (!Directory.Exists(signedFolder))
                            {
                                Directory.CreateDirectory(signedFolder);
                            }

                            // Generate destination path for signed file
                            var signedFile = signedFolder + "/" + filename;

                            // Convert X509Certificate2 to X509Certificate
                            X509CertificateParser certParse = new Org.BouncyCastle.X509.X509CertificateParser();
                            Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { certParse.ReadCertificate(cert.RawData) };

                            // Reader and stamper
                            PdfReader  pdfReader = new PdfReader(file);
                            Stream     signedPdf = new FileStream(signedFile, FileMode.Create);
                            PdfStamper stamper   = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0', null, cbMultiSign.Checked);

                            // Appearance
                            PdfSignatureAppearance appearance = stamper.SignatureAppearance;
                            appearance.SignatureCreator = "PDF Signer 1.0";
                            if (txtReason.Text != "")
                            {
                                appearance.Reason = txtReason.Text;
                            }
                            if (txtLocation.Text != "")
                            {
                                appearance.Location = txtLocation.Text;
                            }

                            // Timestamp
                            TSAClientBouncyCastle tsc = null;
                            if (cbSignWithTSA.Checked == true)
                            {
                                tsc = new TSAClientBouncyCastle("http://ts.cartaodecidadao.pt/tsa/server", "", "");
                            }

                            // Digital signature
                            X509Certificate2Signature externalSignature = new X509Certificate2Signature(cert, "SHA-1");
                            MakeSignature.SignDetached(appearance, externalSignature, chain, null, null, tsc, 0, CryptoStandard.CMS);

                            stamper.Close();
                        }
                        catch (System.IO.IOException)
                        {
                            MessageBox.Show("File not found",
                                            "Error!",
                                            MessageBoxButtons.OK,
                                            MessageBoxIcon.Exclamation);
                        }
                    }

                    // Remove all files from listbox
                    lbFilesToSign.Items.Clear();
                    btnRemoveFile.Enabled = false;
                    btnSignNow.Enabled    = false;
                    MessageBox.Show("You have successfully signed the document(s)", "Success!");
                }
                else
                {
                    MessageBox.Show("Certificate not found.",
                                    "Error!",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Exclamation);
                    return;
                }
            }
            catch (System.Security.Cryptography.CryptographicException)
            {
            }
            catch (System.Net.WebException)
            {
                MessageBox.Show("You must have an internet connection to use timestamp server.",
                                "Error!",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation);
            }
            catch (Exception)
            {
                MessageBox.Show("Oops.. Something wrong.",
                                "Error!",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation);
            }
            finally
            {
                // Set default cursor
                this.Cursor = Cursors.Default;

                if (lblStatus.Text.Contains("A assinar o file"))
                {
                    lblStatus.Text = "Card Inserted.";
                }
            }
        }
Beispiel #19
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();
        }
        public static void signPDF_old(DocumentData doc, Dictionary<String, String> metadata)
        {
            ILog Log;
            Log = LogManager.GetLogger(Properties.Settings.Default.logName);
            try
            {
                PdfReader reader = new PdfReader(doc.Docsignedpath);
                if (File.Exists(doc.Docsignedpath + "-signed.pdf"))
                    File.Delete(doc.Docsignedpath + "-signed.pdf");
                FileStream fos = new FileStream(doc.Docsignedpath + "-signed.pdf", FileMode.CreateNew, FileAccess.Write);

                doc.Docsignedpath = doc.Docsignedpath + "-signed.pdf";
                Log.Debug(String.Format("Creating Stamper for doc {0}", doc.Docname));
                PdfStamper stp = PdfStamper.CreateSignature(reader, fos, '\x002', null, true);
                Log.Debug(String.Format("Creating Certificate for doc {0}", doc.Docname));
                Org.BouncyCastle.X509.X509Certificate[] chain = crearCertificado();
                Log.Debug(String.Format("Reading private key for doc {0}", doc.Docname));
                AsymmetricKeyParameter pk = readPrivateKey();
                stp.Writer.CloseStream = false;
                LtvVerification v = stp.LtvVerification;
                AcroFields af = stp.AcroFields;
                Log.Debug(String.Format("Adding metadata for doc {0}", doc.Docname));
                stp.MoreInfo = metadata;
                foreach (String sigName in af.GetSignatureNames())
                {
                    v.AddVerification(sigName, new OcspClientBouncyCastle(), new CrlClientOffline(null), LtvVerification.CertificateOption.WHOLE_CHAIN, LtvVerification.Level.OCSP_CRL, LtvVerification.CertificateInclusion.NO);
                }
                PdfSignatureAppearance sap = stp.SignatureAppearance;
                sap.Reason = "";
                sap.Location = "";
                //Preserve some space for the contents
                int contentEstimated = 15000;
                Dictionary<PdfName, int> exc = new Dictionary<PdfName, int>();
                exc.Add(PdfName.CONTENTS, (contentEstimated * 2 + 2));
                //Add timestamp

                Log.Debug(String.Format("Adding timestamp for doc {0}", doc.Docname));
                TSAClientBouncyCastle tsc = new TSAClientBouncyCastle(Properties.Settings.Default.tsaUrl, Properties.Settings.Default.tsaUser, Properties.Settings.Default.tsaPass, contentEstimated, DigestAlgorithms.SHA512);
                // Creating the signature
                //LtvTimestamp.Timestamp(sap, tsc, null);
                //Org.BouncyCastle.Crypto.BouncyCastleDigest messageDigest = MessageDigest.getInstance("SHA1");
                //IExternalDigest digest = new Org.BouncyCastle.Crypto.BouncyCastleDigest();
                //RSACryptoServiceProvider crypt = (RSACryptoServiceProvider)cert.PrivateKey;
                Log.Debug(String.Format("Dreating signature for doc {0}", doc.Docname));
                IExternalSignature signature = new PrivateKeySignature(pk, DigestAlgorithms.SHA512);
                MakeSignature.SignDetached(sap, signature, chain, null, null, tsc, 0, CryptoStandard.CMS);
                Log.Debug(String.Format("Closing file for doc {0}", doc.Docname));
                stp.Close();
                fos.Close();
                reader.Close();
            }
            catch (IOException ex)
            {
                Log.Error("IOException", ex);
            }
            catch (DocumentException dex)
            {
                Log.Error("DocumentException", dex);
            }
        }
Beispiel #21
0
        public void Button3Click(object sender, System.EventArgs e)
        {
            if (inputBox.Text != null)
            {
                string filePDF = inputBox.Text;
                try
                {
                    X509Certificate2 card = GetCertificate();
                    Org.BouncyCastle.X509.X509CertificateParser cp    = new Org.BouncyCastle.X509.X509CertificateParser();
                    Org.BouncyCastle.X509.X509Certificate[]     chain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(card.RawData) };

                    //ricreo il percorso con il nome del novo file

                    string    file      = filePDF.Substring(1 + filePDF.LastIndexOf(@"\")).ToLowerInvariant();
                    string    NuovoFile = filePDF.Substring(0, filePDF.LastIndexOf(@"\") + 1) + file.Substring(0, file.LastIndexOf(".")) + "_firmato.pdf".ToLowerInvariant();
                    PdfReader reader    = new PdfReader(filePDF);


                    PdfStamper             stp = PdfStamper.CreateSignature(reader, new FileStream(NuovoFile, FileMode.Create), '\0', null, multiSigChkBx.Checked);
                    PdfSignatureAppearance sap = stp.SignatureAppearance;

                    if (tsaCbx.Checked)
                    {
                        ITSAClient tsc = new TSAClientBouncyCastle(TSAUrlTextBox.Text, tsaLogin.Text, tsaPwd.Text);
                    }

                    if (SigVisible.Checked)
                    {
                        sap.Reason   = cbRagioneSingolo.Text;
                        sap.Contact  = Contacttext.Text;
                        sap.Location = Locationtext.Text;

                        if (sigImgBox.Image != null)
                        {
                            MemoryStream ms = new MemoryStream();
                            sigImgBox.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
                            sap.Image = ms.ToArray() == null ? null : iTextSharp.text.Image.GetInstance(ms.ToArray());
                            ms.Close();
                        }
                        sap.SetVisibleSignature(new iTextSharp.text.Rectangle((float)sigPosX.Value,
                                                                              (float)sigPosY.Value,
                                                                              (float)sigPosX.Value + (float)sigWidth.Value,
                                                                              (float)sigPosY.Value + (float)sigHeight.Value),
                                                Convert.ToInt32(numberOfPagesUpDown.Value),
                                                null);
                    }

                    sap.SignDate = DateTime.Now;
                    sap.SetCrypto(null, chain, null, null);

                    sap.Acro6Layers = true;
                    sap.Render      = PdfSignatureAppearance.SignatureRender.Description;                //.NameAndDescription;
                    PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
                    dic.Date = new PdfDate(sap.SignDate);
                    dic.Name = PdfPKCS7.GetSubjectFields(chain[0]).GetField("CN");

                    if (sap.Reason != null)
                    {
                        dic.Reason = sap.Reason;
                    }
                    if (sap.Location != null)
                    {
                        dic.Location = sap.Location;
                    }
                    if (sap.Contact != null)
                    {
                        dic.Contact = sap.Contact;
                    }
                    sap.CryptoDictionary = dic;
                    int contentEstimated          = 15000;
                    Dictionary <PdfName, int> exc = new Dictionary <PdfName, int>();
                    exc[PdfName.CONTENTS] = contentEstimated * 2 + 2;
                    sap.PreClose(exc);
                    IDigest      messageDigest = DigestUtilities.GetDigest("SHA256");                //add
                    Stream       s             = sap.GetRangeStream();
                    MemoryStream ss            = new MemoryStream();
                    int          read          = 0;
                    byte[]       buff          = new byte[8192];
                    while ((read = s.Read(buff, 0, 8192)) > 0)
                    {
                        ss.Write(buff, 0, read);
                        messageDigest.BlockUpdate(buff, 0, read);                         //add
                    }
                    //--------------------------------------------
                    byte[] hash = new byte[messageDigest.GetDigestSize()];
                    messageDigest.DoFinal(hash, 0);
                    DateTime cal  = DateTime.Now;
                    byte[]   ocsp = null;
                    if (chain.Length >= 2)
                    {
                        String url = PdfPKCS7.GetOCSPURL(chain[0]);
                        if (url != null && url.Length > 0)
                        {
                            ocsp = new OcspClientBouncyCastle().GetEncoded(chain[0], chain[1], url);
                            MessageBox.Show(ocsp.ToString());
                        }
                    }

                    //-------------------------------------------------------------------
                    //TEST TIMESTAMP CON BOUNCYCASTLE
                    //-------------------------------------------------------------------

                    /*
                     * TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator();
                     * // Dummy request
                     * TimeStampRequest request = reqGen.Generate(TspAlgorithms.Sha1, hash, BigInteger.ValueOf(100));
                     * byte[] reqData = request.GetEncoded();
                     * HttpWebRequest httpReq = (HttpWebRequest) WebRequest.Create("http://localhost:8080/signserver/process?workerId=1");
                     * httpReq.Method = "POST";
                     * httpReq.ContentType = "application/timestamp-query";
                     * httpReq.ContentLength = reqData.Length;
                     * // Write the request content
                     * Stream reqStream = httpReq.GetRequestStream();
                     * reqStream.Write(reqData, 0, reqData.Length);
                     * reqStream.Close();
                     * HttpWebResponse httpResp = (HttpWebResponse) httpReq.GetResponse();
                     * // Read the response
                     * Stream respStream = new BufferedStream(httpResp.GetResponseStream());
                     * TimeStampResponse response = new TimeStampResponse(respStream);
                     * respStream.Close();
                     * //MessageBox.Show(response.TimeStampToken.TimeStampInfo.GenTime.ToString());
                     */
                    //-------------------------------------------------------------------
                    //TEST TIMESTAMP CON BOUNCYCASTLE
                    //-------------------------------------------------------------------

                    //===================================QUI FIRMO
                    byte[] pk;
                    if (tsaCbx.Checked)
                    {
                        pk = SignMsg(ss.ToArray(), card, true, tsaCbx.Checked, TSAUrlTextBox.Text, tsaLogin.Text, tsaPwd.Text);
                    }
                    else
                    {
                        pk = SignMsg(ss.ToArray(), card, true, tsaCbx.Checked, "", "", "");
                    }
                    //--------------------------------------------
                    byte[] outc = new byte[contentEstimated];

                    PdfDictionary dic2 = new PdfDictionary();

                    Array.Copy(pk, 0, outc, 0, pk.Length);

                    dic2.Put(PdfName.CONTENTS, new PdfString(outc).SetHexWriting(true));
                    sap.Close(dic2);
                    MessageBox.Show("File firmato correttamente", "Operazione Completata");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }
Beispiel #22
0
        private DocuResponse SignDocumentWithPin(DocuRequest doc)
        {
            //Sign from SmartCard
            //note : ProviderName and KeyContainerName can be found with the dos command : CertUtil -ScInfo
            DocuResponse respo = new DocuResponse();


            X509Store store = new X509Store(StoreLocation.CurrentUser);

            store.Open(OpenFlags.ReadOnly);
            X509Certificate2 cert = null;

            if (doc.ProviderName == "")
            {
                respo.HasError     = true;
                respo.ErrorMessage = "Per te firmosur me certifikaten tuaj duhet te jepni Provider Name";
                return(respo);
            }
            foreach (X509Certificate2 cert2 in store.Certificates)
            {
                if (cert2.HasPrivateKey)
                {
                    RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert2.PrivateKey;
                    if (rsa == null)
                    {
                        continue;                               // not smart card cert again
                    }
                    if (rsa.CspKeyContainerInfo.HardwareDevice) // sure - smartcard
                    {
                        if (rsa.CspKeyContainerInfo.ProviderName == doc.ProviderName)
                        {
                            //we found it
                            cert = cert2;
                            break;
                        }
                    }
                }
            }
            if (cert == null)
            {
                respo.HasError     = true;
                respo.ErrorMessage = "Certifikata nuk u gjet!";
                return(respo);
            }

            if (doc.PinCode != "")
            {
                //if pin code is set then no windows form will popup to ask it
                RSACryptoServiceProvider rsaForKeyContainer = (RSACryptoServiceProvider)cert.PrivateKey;
                SecureString             pwd = GetSecurePin(doc.PinCode);
                CspParameters            csp = new CspParameters(1,
                                                                 doc.ProviderName,
                                                                 rsaForKeyContainer.CspKeyContainerInfo.KeyContainerName,
                                                                 new System.Security.AccessControl.CryptoKeySecurity(),
                                                                 pwd);
                try
                {
                    RSACryptoServiceProvider rsaCsp = new RSACryptoServiceProvider(csp);
                }
                catch (Exception ex)
                {
                    respo.HasError     = true;
                    respo.ErrorMessage = "Crypto error: " + ex.Message;
                    respo.StackTrace   = ex.StackTrace;
                    return(respo);
                }
            }

            //sign


            Org.BouncyCastle.X509.X509CertificateParser cp    = new Org.BouncyCastle.X509.X509CertificateParser();
            Org.BouncyCastle.X509.X509Certificate[]     chain = new Org.BouncyCastle.X509.X509Certificate[] {
                cp.ReadCertificate(cert.RawData)
            };

            IExternalSignature externalSignature = new X509Certificate2Signature(cert, "SHA-1");

            PdfReader pdfReader;

            using (pdfReader = new PdfReader(doc.BasePdf))
            {
                using (signedPdf_mem = new MemoryStream())
                {
                    pdfStamper = PdfStamper.CreateSignature(pdfReader, signedPdf_mem, '\0');
                    PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance;
                    if (doc.SignImage != null && doc.SignImage.Length != 0)
                    {
                        signatureAppearance.SignatureGraphic       = iTextSharp.text.Image.GetInstance(doc.SignImage);
                        signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION;
                    }
                    else
                    {
                        signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.NAME_AND_DESCRIPTION;
                    }
                    signatureAppearance.SetVisibleSignature(new iTextSharp.text.Rectangle(100, 100, 250, 150), pdfReader.NumberOfPages, "NisaDigiSign");
                    signatureAppearance.Reason = "Certifikuar elektronikisht nga sistemi NISA";

                    ITSAClient TsaClient = new TSAClientBouncyCastle(doc.timestampServer);

                    MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, TsaClient, 0, CryptoStandard.CMS);

                    respo.SignedPdf = signedPdf_mem.ToArray();
                }
            }

            return(respo);
        }
Beispiel #23
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());
        }
Beispiel #24
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);
            }
        }
Beispiel #25
0
        private static async Task Main(string[] args)
        {
            Console.WriteLine("CMD Signing Docs Demo...");

            var amaOptions = LoadFromJsonFile();
            var amaCert    = LoadAmaCertificate();



            var encryptionHelper = new EncryptionHelper(amaCert);
            var amaService       = new AmaSigningService(amaOptions,
                                                         encryptionHelper);

            Console.WriteLine("Please introduce your phone number: ");
            var phoneNumber = Console.ReadLine();

            var userCertificatesChain = await amaService.GetUserCertificateChainAsync(phoneNumber !);

            var pdfToBeSigned = "d:\\code\\ama\\doc1.pdf";
            var temporaryPdf  = "d:\\code\\ama\\doc1_int.pdf";
            var finalPdf      = "d:\\code\\ama\\doc1_signed.pdf";

            // freetsa -> config information: https://www.freetsa.org/guide/demonstration-digitally-signed-PDF-documents.html
            var tsaClient = new TSAClientBouncyCastle("https://freetsa.org/tsr");
            // crl list for revocation
            var crlClients = new List <ICrlClient> {
                new CrlClientOnline(userCertificatesChain.ToArray())
            };
            // added ocsp client
            var ocspClient = new OcspClientBouncyCastle(null);

            var pdfSigner = new PdfSigningManager(userCertificatesChain,
                                                  crlClients: crlClients,
                                                  ocspClient: ocspClient,
                                                  tsaClient: tsaClient);
            var pathToLogo      = "d:\\code\\ama\\logo.jpg";
            var logo            = ImageDataFactory.CreateJpeg(new Uri(pathToLogo));
            var hashInformation = pdfSigner.CreateTemporaryPdfForSigning(new SigningInformation(pdfToBeSigned,
                                                                                                temporaryPdf,
                                                                                                Reason: "Because yes",
                                                                                                Location: "Funchal",
                                                                                                Logo: logo));

            Console.WriteLine("Please introduce your CMD signing pin: ");
            var cmdSigningPin = ReadSecretValueFromConsole();


            var processId = await amaService.StartDocSigningProcessAsync(hashInformation.HashForSigning,
                                                                         "Doc1.pdf",
                                                                         phoneNumber !,
                                                                         cmdSigningPin !);

            Console.WriteLine($"{Environment.NewLine}Please introduce the PIN you've received on your phone");
            var otpCode = Console.ReadLine();

            var signature = await amaService.ConfirmDocSigningAsync(otpCode !, processId);

            pdfSigner.SignIntermediatePdf(new SignatureInformation(temporaryPdf,
                                                                   finalPdf,
                                                                   signature,
                                                                   hashInformation.NakedHash,
                                                                   null));

            Console.WriteLine("Document signed");

            Process.Start("cmd.exe ", $"/c {finalPdf}");
        }
Beispiel #26
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);
        }
Beispiel #27
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);
        }
Beispiel #28
0
        public static void AssinaComToken(Stream File, out byte[] SignFile, CertSimples cert, float X, float 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-1", 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 = 155;
            int Altura  = 63;

            Org.BouncyCastle.X509.X509CertificateParser cp    = new Org.BouncyCastle.X509.X509CertificateParser();
            Org.BouncyCastle.X509.X509Certificate[]     chain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(cert.Certificado.RawData) };
            IExternalSignature externalSignature = new X509Certificate2Signature(cert.Certificado, MyDigestAlgorithm);
            PdfReader          pdfReader         = new PdfReader(File);
            MemoryStream       signedPdf         = new MemoryStream();
            //cria a assinatura
            //PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0', "temp" + signedPdf, true);

            string path = System.AppDomain.CurrentDomain.BaseDirectory + "Temp\\";

            PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0', path + DateTime.Now.ToString("hhMMddHHmmss") + ".pdf", true);

            Bitmap bmp = Graphic.ConfiguraBMP(cert, out Altura, Tipo);
            PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance;

            ConfiguraAparenciaAssinatura(signatureAppearance, Reason, Contact, Location, Creator, bmp, Altura, Largura, X, Y, Rotation, Pagina, pdfReader);

            TSAClientBouncyCastle tsaClient = null;

            if (AddTimeStamper)
            {
                tsaClient = new TSAClientBouncyCastle(urlTimeStamper, timeStampUser, timeStampPass, TSAClientBouncyCastle.DEFAULTTOKENSIZE, MyDigestAlgorithm);
            }

            IOcspClient       ocspClient = new OcspClientBouncyCastle();
            List <ICrlClient> crlList    = new List <ICrlClient>();

            crlList.Add(new CrlClientOnline(chain));



            if (AplicaPolitica)
            {
                SignaturePolicyInfo spi = PoliticaDaAssinatura();
                MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, crlList, ocspClient, tsaClient, 0, CryptoStandard.CADES, spi);
            }
            else
            {
                MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, crlList, ocspClient, tsaClient, 0, CryptoStandard.CADES);
            }

            try
            {
                SignFile = signedPdf.ToArray();
                //SignFile = INB.Assinador.Helper.Funcoes.ToByteArray(teste);

                //MemoryStream teste = (MemoryStream)signatureAppearance.TempFile;

                //signedPdf.Flush();
                //SignFile
                // SignFile = new MemoryStream(ArquivoAssinado);
                // signedPdf.CopyTo();
                try
                {
                    signedPdf.Close();
                    signedPdf.Dispose();
                }
                catch { }
            }
            catch (Exception ex)
            {
                SignFile = null;
                throw ex;
            }
            try
            {
                signedPdf.Close();
            }
            catch (Exception ex) {}
            pdfReader.Close();
            try
            {
                pdfReader.Dispose();
            }
            catch { }
        }
Beispiel #29
0
        private void SignPdf(Stream input, Stream output, X509Certificate2 cert)
        {
            var bcCert = DotNetUtilities.FromX509Certificate(cert);
            var bcKey = DotNetUtilities.GetKeyPair(cert.PrivateKey);

            var signature = new PrivateKeySignature(bcKey.Private, "SHA-512");

            var tsaClient = new TSAClientBouncyCastle("http://timestamp.globalsign.com/scripts/timestamp.dll");

            using (var reader = new PdfReader(input))
            using (var stamper = PdfStamper.CreateSignature(reader, output, '\0'))
            {
                MakeSignature.SignDetached(stamper.SignatureAppearance, signature, new[] { bcCert }, null, null, tsaClient, 0, CryptoStandard.CMS);
            }
        }
Beispiel #30
0
        //public static void AssinaComToken_OLD(string FileName, string SignFileName, X509Certificate2 cert, float X, float Y, int Pagina, double Escala, bool SeloCargo = false, bool SeloCREA = false, bool SeloCRM = false, string Cargo = "", string CREACRM = "", bool AddTimeStamper = true, string urlTimeStamper = "https://freetsa.org/tsr", string timeStampUser = "", string timeStampPass = "", string Reason = "Assinatura Digital", bool AplicaPolitica = false, string MyDigestAlgorithm = "SHA-1", string Contact = "", string Location = "Indústrias Nucleares do Brasil S/A - INB", string Creator = "Assinador da INB", bool SeloCertifico = false)
        //{
        //    string SourcePdfFileName = FileName;
        //    string DestPdfFileName = SignFileName;
        //    int Largura = 155;
        //    int Altura = 63;
        //    Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser();
        //    Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(cert.RawData) };
        //    IExternalSignature externalSignature = new X509Certificate2Signature(cert, MyDigestAlgorithm);
        //    PdfReader pdfReader = new PdfReader(SourcePdfFileName);
        //    FileStream signedPdf = new FileStream(DestPdfFileName, FileMode.Create, FileAccess.ReadWrite);  //the output pdf file
        //                                                                                                    //cria a assinatura
        //    PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0', "temp" + signedPdf, true);
        //    PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance;
        //    Bitmap bmp = INB.Assinador.Helper.Graphic.ConfiguraBMP(cert, SeloCargo, SeloCREA, SeloCRM, Cargo, CREACRM, out Altura, SeloCertifico);

        //    //CONFIGURA A APARÊNCIA DO SELO DA ASSINATURA.
        //    ConfiguraAparenciaAssinatura(signatureAppearance, Reason, Contact, Location, Creator, bmp, Altura, Largura, X, Y, Escala, Pagina, pdfReader);

        //    //ADICIONA O CARIMBO DO TEMPO.
        //   TSAClientBouncyCastle tsaClient = null;
        //    if (AddTimeStamper)
        //    {
        //        //urlTimeStamper = http://timestamp.globalsign.com/scripts/timestamp.dll
        //        //urlTimeStamper = "http://timestamp.apple.com/ts01";
        //        tsaClient = new TSAClientBouncyCastle(urlTimeStamper, timeStampUser, timeStampPass, TSAClientBouncyCastle.DEFAULTTOKENSIZE, MyDigestAlgorithm);
        //    }
        //    IOcspClient ocspClient = new OcspClientBouncyCastle();
        //    List<ICrlClient> crlList = new List<ICrlClient>();
        //    crlList.Add(new CrlClientOnline(chain));

        //    //Nota 2: O hash da política de assinatura no atributo id-aa-ets-sigPolicyId da assinatura deve ser o hash interno que está na própria PA e não o hash da PA que se encontra publicada na LPA.
        //    if (AplicaPolitica)
        //    {
        //            SignaturePolicyInfo spi = PoliticaDaAssinatura();
        //        MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, crlList, ocspClient, tsaClient, 0, CryptoStandard.CADES, spi);
        //    }
        //    else
        //    {
        //        MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, crlList, ocspClient, tsaClient, 0, CryptoStandard.CADES);
        //    }
        //    try { signedPdf.Flush(); }
        //    catch { }
        //    try { signedPdf.Close(); } catch { };
        //    pdfReader.Close();
        //    try {
        //    pdfReader.Dispose();
        //    }
        //    catch { }
        //}

        public static void AssinaComToken(string FileName, string SignFileName, CertSimples cert, float X, float 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-1", 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           = 155;
            int    Altura            = 63;

            Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser();

            Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(cert.Certificado.RawData) };


            //IExternalSignature externalSignature = new X509Certificate2Signature(cert.Certificado, MyDigestAlgorithm);

            RSACryptoServiceProvider rsa;
            RSACryptoServiceProvider Provider;
            IExternalSignature       externalSignature = null;


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

            PdfReader  pdfReader = new PdfReader(SourcePdfFileName);
            FileStream signedPdf = new FileStream(DestPdfFileName, FileMode.Create, FileAccess.ReadWrite); //the output pdf file

            string     path       = System.AppDomain.CurrentDomain.BaseDirectory + "Temp\\";               //cria a assinatura
            PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0', path + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf", true);

            PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance;
            Bitmap bmp = INB.Assinador.Model.Graphic.ConfiguraBMP(cert, out Altura, Tipo);

            //CONFIGURA A APARÊNCIA DO SELO DA ASSINATURA.
            ConfiguraAparenciaAssinatura(signatureAppearance, Reason, Contact, Location, Creator, bmp, Altura, Largura, X, Y, Rotation, Pagina, pdfReader);

            //ADICIONA O CARIMBO DO TEMPO.
            TSAClientBouncyCastle tsaClient = null;

            if (AddTimeStamper)
            {
                //urlTimeStamper = http://timestamp.globalsign.com/scripts/timestamp.dll
                //urlTimeStamper = "http://timestamp.apple.com/ts01";
                tsaClient = new TSAClientBouncyCastle(urlTimeStamper, timeStampUser, timeStampPass, TSAClientBouncyCastle.DEFAULTTOKENSIZE, MyDigestAlgorithm);
            }
            IOcspClient       ocspClient = new OcspClientBouncyCastle();
            List <ICrlClient> crlList    = new List <ICrlClient>();

            crlList.Add(new CrlClientOnline(chain));

            //Nota 2: O hash da política de assinatura no atributo id-aa-ets-sigPolicyId da assinatura deve ser o hash interno que está na própria PA e não o hash da PA que se encontra publicada na LPA.
            if (AplicaPolitica)
            {
                SignaturePolicyInfo spi = PoliticaDaAssinatura();
                MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, crlList, ocspClient, tsaClient, 0, CryptoStandard.CADES, spi);
            }
            else
            {
                MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, crlList, ocspClient, tsaClient, 0, CryptoStandard.CADES);
            }
            try { signedPdf.Flush(); }
            catch { }
            try { signedPdf.Close(); } catch { };
            pdfReader.Close();
            try
            {
                pdfReader.Dispose();
            }
            catch { }
        }
Beispiel #31
0
        static int Main(string[] args)
        {
            if (args.Length == 0)
            {
                PrintUsage();
                return((int)ExitCode.Success);
            }

            Arguments.Populate();

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

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

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

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

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

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


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

                // Build certification path for the signing certificate
                ICollection <Org.BouncyCastle.X509.X509Certificate> certPath = eidSignature.BuildCertPath(signingCertificate, otherCertificates);

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

                // Read unsigned PDF document
                using (PdfReader pdfReader = new PdfReader(SourceFile))
                {
                    string tmpSigned = Path.GetTempFileName();

                    // Create output stream for signed PDF document
                    using (FileStream outputStream = new FileStream(tmpSigned, FileMode.Create))
                    {
                        // Create PdfStamper that applies extra content to the PDF document
                        using (PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, outputStream, '\0'))
                        {
                            PdfSignatureAppearance appearance = pdfStamper.SignatureAppearance;

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

                            // Sign PDF document
                            try
                            {
                                MakeSignature.SignDetached(appearance, eidSignature, certPath, crlList, null, tsaClient, 0, CryptoStandard.CADES);
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e.Message);
                                return((int)ExitCode.UnknownError);
                            }
                        }
                    }

                    try
                    {
                        AddLtv(tmpSigned, DestinationFile, null, new CrlClientOnline(), tsaClient);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                        return((int)ExitCode.UnknownError);
                    }
                }
            }

            return((int)ExitCode.Success);
        }
Beispiel #32
0
        public static void Main(String[] args)
        {
            DirectoryInfo directory = new DirectoryInfo(DEST);

            directory.Create();

            Properties properties = new Properties();

            // Specify the correct path to the certificate
            properties.Load(new FileStream("c:/home/blowagie/key.properties", FileMode.Open, FileAccess.Read));
            String path = properties.GetProperty("PRIVATE");

            char[] pass    = properties.GetProperty("PASSWORD").ToCharArray();
            String tsaUrl  = properties.GetProperty("TSAURL");
            String tsaUser = properties.GetProperty("TSAUSERNAME");
            String tsaPass = properties.GetProperty("TSAPASSWORD");

            Pkcs12Store pk12  = new Pkcs12Store(new FileStream(path, FileMode.Open, FileAccess.Read), pass);
            string      alias = null;

            foreach (var a in pk12.Aliases)
            {
                alias = ((string)a);
                if (pk12.IsKeyEntry(alias))
                {
                    break;
                }
            }

            ICipherParameters pk = pk12.GetKey(alias).Key;

            X509CertificateEntry[] ce    = pk12.GetCertificateChain(alias);
            X509Certificate[]      chain = new X509Certificate[ce.Length];
            for (int k = 0; k < ce.Length; ++k)
            {
                chain[k] = ce[k].Certificate;
            }

            IOcspClient ocspClient          = new OcspClientBouncyCastle(null);
            ITSAClient  tsaClient           = new TSAClientBouncyCastle(tsaUrl, tsaUser, tsaPass);
            C3_12_SignWithEstimatedSize app = new C3_12_SignWithEstimatedSize();

            bool succeeded     = false;
            int  estimatedSize = 1000;

            while (!succeeded)
            {
                try
                {
                    Console.WriteLine("Attempt: " + estimatedSize + " bytes");

                    app.Sign(SRC, DEST, chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS,
                             "Test", "Ghent", null, ocspClient, tsaClient, estimatedSize);

                    succeeded = true;
                    Console.WriteLine("Succeeded!");
                }
                catch (IOException ioe)
                {
                    Console.WriteLine("Not succeeded: " + ioe.Message);
                    estimatedSize += 50;
                }
            }
        }
        /**
         *
         *
         */
        public static void signPDF(DocumentData doc, String metadata, GraphSign sign, Signer signer)
        {
            ILog Log;
            Log = LogManager.GetLogger(Properties.Settings.Default.logName);
            if (!File.Exists(doc.Docsignedpath /*+ "-signed.pdf"*/))
            {
                File.Copy(doc.Docpath, doc.Docsignedpath);
            }
            try
            {
                PdfReader reader = new PdfReader(doc.Docsignedpath);
                if (File.Exists(doc.Docsignedpath + "-signed.pdf"))
                    File.Delete(doc.Docsignedpath + "-signed.pdf");
                FileStream fos = new FileStream(doc.Docsignedpath + "-signed.pdf", FileMode.CreateNew, FileAccess.Write);

                doc.Docsignedpath = doc.Docsignedpath + "-signed.pdf";
                Log.Debug(String.Format("Creating Stamper for doc {0}",doc.Docname));
                PdfStamper stp = PdfStamper.CreateSignature(reader, fos, '\0', null, true);
                Log.Debug(String.Format("Creating Certificate for doc {0}", doc.Docname));
                Org.BouncyCastle.X509.X509Certificate[] chain = crearCertificado();
                Log.Debug(String.Format("Reading private key for doc {0}", doc.Docname));
                AsymmetricKeyParameter pk = readPrivateKey();
                stp.Writer.CloseStream = false;
                LtvVerification v = stp.LtvVerification;
                //AcroFields af = stp.AcroFields;
                Log.Debug(String.Format("Adding metadata for doc {0}", doc.Docname));
                //stp.MoreInfo = metadata;
             //               foreach (String sigName in af.GetSignatureNames())
             //               {
             //                   v.AddVerification(sigName, new OcspClientBouncyCastle(), new CrlClientOffline(null), LtvVerification.CertificateOption.WHOLE_CHAIN, LtvVerification.Level.OCSP_CRL, LtvVerification.CertificateInclusion.NO);
            //                }
                PdfSignatureAppearance sap = stp.SignatureAppearance;
                //sap.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION;
                sap.Reason = metadata;
                sap.Location = "";
                sign.Image.MakeTransparent();
                sap.Image = iTextSharp.text.Image.GetInstance(sign.Image,  System.Drawing.Imaging.ImageFormat.Png);
                sap.Layer2Text = "";

                //Preserve some space for the contents
                int contentEstimated = 15000;
                Dictionary<PdfName, int> exc = new Dictionary<PdfName, int>();
                exc.Add(PdfName.CONTENTS, (contentEstimated * 2 + 2));
                //Add timestamp

                Log.Debug(String.Format("Adding timestamp for doc {0}", doc.Docname));
                TSAClientBouncyCastle tsc  = new TSAClientBouncyCastle(Properties.Settings.Default.tsaUrl, Properties.Settings.Default.tsaUser, Properties.Settings.Default.tsaPass, contentEstimated, DigestAlgorithms.SHA512);
                // Creating the signature
                //LtvTimestamp.Timestamp(sap, tsc, null);
                //Org.BouncyCastle.Crypto.BouncyCastleDigest messageDigest = MessageDigest.getInstance("SHA1");
                //IExternalDigest digest = new Org.BouncyCastle.Crypto.BouncyCastleDigest();
                //RSACryptoServiceProvider crypt = (RSACryptoServiceProvider)cert.PrivateKey;
                Log.Debug(String.Format("Dreating signature for doc {0}", doc.Docname));
                IExternalSignature signature = new PrivateKeySignature(pk, DigestAlgorithms.SHA512);
                sap.Layer2Text = "Huella: "+signature.GetHashCode();
                sap.SetVisibleSignature(new Rectangle(signer.X, signer.Y, 200, 200), signer.Page, signer.Nombre+index);
                MakeSignature.SignDetached(sap, signature, chain, null, null, tsc, 0, CryptoStandard.CMS);
                Log.Debug(String.Format("Closing file for doc {0}", doc.Docname));
                stp.Close();
                fos.Close();
                reader.Close();
            }
            catch (IOException ex)
            {
                Log.Error("IOException", ex);
            }
            catch (DocumentException dex)
            {
                Log.Error("DocumentException", dex);
            }
        }