static byte[] GetCertificateChainOCSP(X509Certificate[] certificateChain)
        {
            byte[] ocsp = null;

            if (certificateChain.Length >= 2)
            {
                String url = PdfPKCS7.GetOCSPURL(certificateChain[0]);
                if (url != null && url.Length > 0)
                {
                    ocsp = new OcspClientBouncyCastle(certificateChain[0], certificateChain[1], url).GetEncoded();
                }
            }
            return(ocsp);
        }
示例#2
0
        public void Sign(PDFSignatureAP sigAP, bool encrypt, PDFEncryption Enc)
        {
            PdfReader reader = new PdfReader(this.inputPDF);

            FileStream fs = new FileStream(this.outputPDF, FileMode.Create, FileAccess.Write);


            PdfStamper st;

            if (this.myCert == null)             //No signature just write meta-data and quit
            {
                st = new PdfStamper(reader, fs);
            }
            else
            {
                st = PdfStamper.CreateSignature(reader, fs, '\0', null, sigAP.Multi);
            }

            if (encrypt && Enc != null)
            {
                Enc.Encrypt(st);
            }
            //st.SetEncryption(PdfWriter.STRENGTH128BITS, "user", "owner", PdfWriter.ALLOW_COPY);

            st.MoreInfo    = this.metadata.getMetaData();
            st.XmpMetadata = this.metadata.getStreamedMetaData();

            if (this.myCert == null)             //No signature just write meta-data and quit
            {
                st.Close();
                return;
            }

            PdfSignatureAppearance sap = st.SignatureAppearance;

            //sap.SetCrypto(this.myCert.Akp, this.myCert.Chain, null, PdfSignatureAppearance.WINCER_SIGNED);

            sap.SetCrypto(null, this.myCert.Chain, null, PdfSignatureAppearance.SELF_SIGNED);

            sap.Reason   = sigAP.SigReason;
            sap.Contact  = sigAP.SigContact;
            sap.Location = sigAP.SigLocation;
            if (sigAP.Visible)
            {
                iTextSharp.text.Rectangle rect = st.Reader.GetPageSize(sigAP.Page);
                sap.Image      = sigAP.RawData == null ? null : iTextSharp.text.Image.GetInstance(sigAP.RawData);
                sap.Layer2Text = sigAP.CustomText;

                sap.SetVisibleSignature(new iTextSharp.text.Rectangle(sigAP.SigX, sigAP.SigY, sigAP.SigX + sigAP.SigW, sigAP.SigY + sigAP.SigH), sigAP.Page, null);
            }



            /////
            PdfSignature 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;

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

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

            PdfPKCS7 sgn           = new PdfPKCS7(this.myCert.Akp, this.myCert.Chain, null, "SHA1", false);
            IDigest  messageDigest = DigestUtilities.GetDigest("SHA1");
            Stream   data          = sap.GetRangeStream();

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

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

            byte[] ocsp = null;
            if (this.myCert.Chain.Length >= 2)
            {
                String url = PdfPKCS7.GetOCSPURL(this.myCert.Chain[0]);
                if (url != null && url.Length > 0)
                {
                    ocsp = new OcspClientBouncyCastle().GetEncoded(this.myCert.Chain[0], this.myCert.Chain[1], url);
                }
            }
            byte[] sh = sgn.GetAuthenticatedAttributeBytes(hash, cal, ocsp);
            sgn.Update(sh, 0, sh.Length);


            byte[] paddedSig = new byte[contentEstimated];


            if (this.myCert.Tsc != null)
            {
                byte[] encodedSigTsa = sgn.GetEncodedPKCS7(hash, cal, this.myCert.Tsc, ocsp);
                System.Array.Copy(encodedSigTsa, 0, paddedSig, 0, encodedSigTsa.Length);
                if (contentEstimated + 2 < encodedSigTsa.Length)
                {
                    throw new Exception("Not enough space for signature");
                }
            }
            else
            {
                byte[] encodedSig = sgn.GetEncodedPKCS7(hash, cal);
                System.Array.Copy(encodedSig, 0, paddedSig, 0, encodedSig.Length);
                if (contentEstimated + 2 < encodedSig.Length)
                {
                    throw new Exception("Not enough space for signature");
                }
            }



            PdfDictionary dic2 = new PdfDictionary();

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

            //////
            //st.Close();
        }
示例#3
0
文件: Signer.cs 项目: masums/clawPDF
        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);
        }
示例#4
0
        public void Sign(PDFSignatureAP sigAP, bool encrypt, PDFEncryption enc)
        {
            byte[] ownerPassword = null;
            if (!string.IsNullOrEmpty(enc.OwnerPwd))
            {
                ownerPassword = DocWriter.GetISOBytes(enc.OwnerPwd);
            }

            PdfReader reader = new PdfReader(this.inputPDF, ownerPassword);

            FileStream fs = new FileStream(this.outputPDF, FileMode.Create, FileAccess.Write);

            PdfStamper st;

            if (this.myCert == null)             //No signature just write meta-data and quit
            {
                st = new PdfStamper(reader, fs);
            }
            else
            {
                st = PdfStamper.CreateSignature(reader, fs, '\0', null, sigAP.Multi);
            }

            if (encrypt && enc != null)
            {
                enc.Encrypt(st);
            }
            //st.SetEncryption(PdfWriter.STRENGTH128BITS, "user", "owner", PdfWriter.ALLOW_COPY);

            st.MoreInfo    = this.metadata.getMetaData();
            st.XmpMetadata = this.metadata.getStreamedMetaData();

            if (this.myCert == null)             //No signature just write meta-data and quit
            {
                st.Close();
                return;
            }

            PdfSignatureAppearance sap = st.SignatureAppearance;

            //sap.SetCrypto(this.myCert.Akp, this.myCert.Chain, null, PdfSignatureAppearance.WINCER_SIGNED);

            sap.SetCrypto(null, this.myCert.Chain, null, PdfSignatureAppearance.SELF_SIGNED);

            sap.Reason   = sigAP.SigReason;
            sap.Contact  = sigAP.SigContact;
            sap.Location = sigAP.SigLocation;
            if (sigAP.Visible)
            {
                iTextSharp.text.Rectangle rect = st.Reader.GetPageSize(sigAP.Page);
                sap.Image      = sigAP.RawData == null ? null : iTextSharp.text.Image.GetInstance(sigAP.RawData);
                sap.Layer2Text = sigAP.CustomText;

                sap.SetVisibleSignature(new iTextSharp.text.Rectangle(sigAP.SigX, sigAP.SigY, sigAP.SigX + sigAP.SigW, sigAP.SigY + sigAP.SigH), sigAP.Page, null);
            }

            // Remove yellow question mark (green check mark is still used though)
            //sap.GetLayer(1);

            // The first signature is a certification
            //if (!sigAP.Multi)
            //{
            //    //sap.CertificationLevel = PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED;
            //    sap.CertificationLevel = PdfSignatureAppearance.CERTIFIED_FORM_FILLING;
            //}

            PdfSignature 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;

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

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

            PdfPKCS7 sgn           = new PdfPKCS7(this.myCert.Akp, this.myCert.Chain, null, "SHA-256", false);
            IDigest  messageDigest = DigestUtilities.GetDigest("SHA-256");
            // change for itextsharp-all-5.2.1
            Stream data = sap.GetRangeStream();

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

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

            byte[] ocsp = null;
            if (this.myCert.Chain.Length >= 2)
            {
                String url = PdfPKCS7.GetOCSPURL(this.myCert.Chain[0]);
                if (url != null && url.Length > 0)
                {
                    //ocsp =  new  OcspClientBouncyCastle(this.myCert.Chain[0], this.myCert.Chain[1], url).GetEncoded();
                    // change for itextsharp-all-5.2.1
                    ocsp = new OcspClientBouncyCastle().GetEncoded(this.myCert.Chain[0], this.myCert.Chain[1], url);
                }
            }
            byte[] sh = sgn.GetAuthenticatedAttributeBytes(hash, cal, ocsp);
            sgn.Update(sh, 0, sh.Length);

            byte[] paddedSig = new byte[contentEstimated];

            if (this.myCert.Tsc != null)
            {
                byte[] encodedSigTsa = sgn.GetEncodedPKCS7(hash, cal, this.myCert.Tsc, ocsp);
                System.Array.Copy(encodedSigTsa, 0, paddedSig, 0, encodedSigTsa.Length);
                if (contentEstimated + 2 < encodedSigTsa.Length)
                {
                    throw new Exception("Not enough space for signature");
                }
            }
            else
            {
                byte[] encodedSig = sgn.GetEncodedPKCS7(hash, cal);
                System.Array.Copy(encodedSig, 0, paddedSig, 0, encodedSig.Length);
                if (contentEstimated + 2 < encodedSig.Length)
                {
                    throw new Exception("Not enough space for signature");
                }
            }

            PdfDictionary dic2 = new PdfDictionary();

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

            //// Lock all fields after signing (backport from iText 5.4.4) - wrong - doesn't work
            //PdfDictionary lockDic = new PdfDictionary(new PdfName("SigFieldLock"));
            //lockDic.Put(PdfName.ACTION, new PdfName("All"));
            //lockDic.Put(PdfName.P, new PdfNumber(1));
            //dic2.Put(PdfName.LOCK, lockDic);

            sap.Close(dic2);

            //st.Close();
        }
示例#5
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());
        }
示例#6
0
        private MemoryStream Assinar2(MemoryStream ArquivoOrigem, X509Certificate2 cert, ref byte[] pkcs7)
        {
            this.card = cert;
            X509CertificateParser x509CertificateParser = new X509CertificateParser();

            Org.BouncyCastle.X509.X509Certificate[] array = new Org.BouncyCastle.X509.X509Certificate[]
            {
                x509CertificateParser.ReadCertificate(this.card.RawData)
            };
            PdfReader              reader              = new PdfReader(ArquivoOrigem);
            MemoryStream           memoryStream        = new MemoryStream();
            PdfStamper             pdfStamper          = PdfStamper.CreateSignature(reader, memoryStream, '\0', null, true);
            PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance;

            signatureAppearance.SetCrypto(null, array, null, PdfSignatureAppearance.SELF_SIGNED);
            signatureAppearance.Reason           = this.proposito;
            signatureAppearance.Contact          = this.contato;
            signatureAppearance.Location         = this.localizacao;
            signatureAppearance.CryptoDictionary = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached"))
            {
                Reason   = signatureAppearance.Reason,
                Location = signatureAppearance.Location,
                Contact  = signatureAppearance.Contact,
                Date     = new PdfDate(signatureAppearance.SignDate)
            };
            int num = 15000;
            Dictionary <PdfName, int> dictionary = new Dictionary <PdfName, int>();

            dictionary[PdfName.CONTENTS] = num * 2 + 2;
            signatureAppearance.PreClose(dictionary);
            //PdfPKCS7 pdfPKCS = new PdfPKCS7(null, array, null, "SHA1", false);
            PdfPKCS7 pdfPKCS     = new PdfPKCS7(null, array, null, "MD5", false);
            IDigest  digest      = DigestUtilities.GetDigest("MD5");
            Stream   rangeStream = signatureAppearance.GetRangeStream();

            byte[] array2 = new byte[8192];
            int    length;

            while ((length = rangeStream.Read(array2, 0, array2.Length)) > 0)
            {
                digest.BlockUpdate(array2, 0, length);
            }
            byte[] array3 = new byte[digest.GetDigestSize()];
            digest.DoFinal(array3, 0);
            DateTime now = DateTime.Now;

            byte[] ocsp = null;
            if (array.Length >= 2)
            {
                string oCSPURL = PdfPKCS7.GetOCSPURL(array[0]);
                if (oCSPURL != null && oCSPURL.Length > 0)
                {
                    ocsp = new OcspClientBouncyCastle().GetEncoded(array[0], array[1], oCSPURL);
                }
            }
            byte[] authenticatedAttributeBytes = pdfPKCS.GetAuthenticatedAttributeBytes(array3, now, ocsp);
            byte[] digest2 = Assinar.SignSHA1withRSA(this.card, authenticatedAttributeBytes);
            pdfPKCS.SetExternalDigest(digest2, array3, "RSA");
            byte[] array4      = new byte[num];
            byte[] encodedPKCS = pdfPKCS.GetEncodedPKCS7(array3, now, null, ocsp);
            pkcs7 = encodedPKCS;
            Array.Copy(encodedPKCS, 0, array4, 0, encodedPKCS.Length);
            if (num + 2 < encodedPKCS.Length)
            {
                throw new ApplicationException("Não há espaço suficiente para assinatura.");
            }
            PdfDictionary pdfDictionary = new PdfDictionary();

            pdfDictionary.Put(PdfName.CONTENTS, new PdfString(array4).SetHexWriting(true));
            signatureAppearance.Close(pdfDictionary);
            //pdfStamper.
            return(memoryStream);
        }
示例#7
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());
                }
            }
        }