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

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

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

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

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

            PdfDictionary dic2 = new PdfDictionary();
            dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true));
            sap.Close(dic2);
        }
        static void PKCS7SignDocument(

            AsymmetricKeyParameter privateKey,
            X509Certificate[] certificateChain,
            PdfSignatureAppearance signatureAppearance,
            string algorithm)
        {
            DateTime timestamp         = signatureAppearance.SignDate;
            PdfPKCS7 pdfPKCS7signature = new PdfPKCS7(privateKey, certificateChain, null, algorithm, false);

            // Get signature hash & certificate chain OCSP

            byte[] hash = CreateMessageDigestHash(signatureAppearance.RangeStream, "SHA-256");
            byte[] ocsp = GetCertificateChainOCSP(certificateChain);

            byte[] authAttributeBytes = pdfPKCS7signature.GetAuthenticatedAttributeBytes(hash, timestamp, ocsp);
            pdfPKCS7signature.Update(authAttributeBytes, 0, authAttributeBytes.Length);

            byte[] encodedSignature = pdfPKCS7signature.GetEncodedPKCS7(hash, timestamp);
            byte[] paddedSignature  = new byte[ContentEstimated];

            System.Array.Copy(encodedSignature, 0, paddedSignature, 0, encodedSignature.Length);

            if (ContentEstimated + 2 < encodedSignature.Length)
            {
                throw new Exception("Not enough space for signature");
            }

            PdfDictionary dict = new PdfDictionary();

            dict.Put(PdfName.CONTENTS, new PdfString(paddedSignature).SetHexWriting(true));
            signatureAppearance.Close(dict);
        }
Esempio n. 3
0
 /// <summary>
 /// Sign the PDF content
 /// </summary>
 /// <param name="signedValue"></param>
 /// <returns>Signed PDF document byte array</returns>
 public byte[] Sign(string signedValue)
 {
     try
     {
         byte[] encodedSignature = Convert.FromBase64String(signedValue);
         byte[] paddedSignature  = new byte[EXCLUSION_BUFFER];
         Array.Copy(encodedSignature, 0, paddedSignature, 0, encodedSignature.Length);
         var pdfDictionary = new PdfDictionary();
         pdfDictionary.Put(
             PdfName.CONTENTS,
             new PdfString(paddedSignature).SetHexWriting(true)
             );
         _signatureAppearance.Close(pdfDictionary);
         return(_memoryStream.ToArray());
     }
     catch (FormatException fe)
     {
         throw new InvalidDataException("invalid signature format");
     }
     catch { throw; }
     finally
     {
         _memoryStream.Dispose();
         HttpContext.Current.Session.Remove(InstanceLookupKey);
     }
 }
Esempio n. 4
0
        /**
         * Sign the document using an external container, usually a PKCS7. The signature is fully composed
         * externally, iText will just put the container inside the document.
         * @param sap the PdfSignatureAppearance
         * @param externalSignatureContainer the interface providing the actual signing
         * @param estimatedSize the reserved size for the signature
         * @throws GeneralSecurityException
         * @throws IOException
         * @throws DocumentException
         */
        public static void SignExternalContainer(PdfSignatureAppearance sap, IExternalSignatureContainer externalSignatureContainer, int estimatedSize)
        {
            PdfSignature dic = new PdfSignature(null, null);

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

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

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

            Stream data = sap.GetRangeStream();

            byte[] encodedSig = externalSignatureContainer.Sign(data);

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

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

            PdfDictionary dic2 = new PdfDictionary();

            dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true));
            sap.Close(dic2);
        }
Esempio n. 5
0
        /**
         * Closes the document. No more content can be written after the
         * document is closed.
         * <p>
         * If closing a signed document with an external signature the closing must be done
         * in the <CODE>PdfSignatureAppearance</CODE> instance.
         * @throws DocumentException on error
         * @throws IOException on error
         */
        public void Close()
        {
            if (!hasSignature)
            {
                stamper.Close(moreInfo);
                return;
            }
            sigApp.PreClose();
            PdfSigGenericPKCS sig = sigApp.SigStandard;
            PdfLiteral        lit = (PdfLiteral)sig.Get(PdfName.CONTENTS);
            int totalBuf          = (lit.PosLength - 2) / 2;

            byte[] buf = new byte[8192];
            int    n;
            Stream inp = sigApp.RangeStream;

            while ((n = inp.Read(buf, 0, buf.Length)) > 0)
            {
                sig.Signer.Update(buf, 0, n);
            }
            buf = new byte[totalBuf];
            byte[] bsig = sig.SignerContents;
            Array.Copy(bsig, 0, buf, 0, bsig.Length);
            PdfString str = new PdfString(buf);

            str.SetHexWriting(true);
            PdfDictionary dic = new PdfDictionary();

            dic.Put(PdfName.CONTENTS, str);
            sigApp.Close(dic);
            stamper.reader.Close();
        }
        private void UpdatePdfDictionaryContents(PdfSignatureAppearance pdfSignatureAppearance, byte[] encodedSignature)
        {
            var pdfDictionary   = new PdfDictionary();
            var paddedSignature = new byte[SIGNATURE_ESTIMATED_SIZE];

            Array.Copy(encodedSignature, 0, paddedSignature, 0, encodedSignature.Length);

            pdfDictionary.Put(PdfName.CONTENTS, new PdfString(paddedSignature).SetHexWriting(true));

            pdfSignatureAppearance.Close(pdfDictionary);
        }
        public byte[] SignPDFToMemory(byte[] pk)
        {
            byte[] paddedSig = new byte[RESERVED_SPACE_SIGNATURE];
            System.Array.Copy(pk, 0, paddedSig, 0, pk.Length);

            PdfDictionary dic2 = new PdfDictionary();

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

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

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

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

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

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

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

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

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

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

            PdfDictionary dic2 = new PdfDictionary();

            dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true));
            sap.Close(dic2);
        }
Esempio n. 9
0
        private static void SetSigCryptoFromX509(PdfSignatureAppearance sigAppearance, X509Certificate2 card, X509Certificate[] chain)
        {
            sigAppearance.SetCrypto(null, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
            var dic = new PdfSignature(PdfName.ADOBE_PPKMS, PdfName.ADBE_PKCS7_SHA1)
            {
                Date     = new PdfDate(sigAppearance.SignDate),
                Name     = PdfPKCS7.GetSubjectFields(chain[0]).GetField("CN"),
                Reason   = sigAppearance.Reason,
                Location = sigAppearance.Location
            };

            sigAppearance.CryptoDictionary = dic;
            const int csize = 4000;
            var       exc   = new Dictionary <PdfName, int> {
                { PdfName.CONTENTS, csize * 2 + 2 }
            };

            sigAppearance.PreClose(exc);

            HashAlgorithm sha = new SHA1CryptoServiceProvider();

            var s = sigAppearance.RangeStream;
            int read;
            var buff = new byte[8192];

            while ((read = s.Read(buff, 0, 8192)) > 0)
            {
                sha.TransformBlock(buff, 0, read, buff, 0);
            }
            sha.TransformFinalBlock(buff, 0, 0);
            var pk = SignMsg(sha.Hash, card, false);

            var outc = new byte[csize];

            var dic2 = new PdfDictionary();

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

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

            sigAppearance.Close(dic2);
        }
Esempio n. 10
0
        private void Sign(string hash)
        {
            try
            {
                byte[] result = System.Convert.FromBase64String(hash);
                sgn.SetExternalDigest(result, null, "RSA");
                byte[] encodesig = sgn.GetEncodedPKCS7(hashValue, null /* tsa client */, null, null, CryptoStandard.CADES);

                sap.Close(this.AttachSignedContent(encodesig));
            }
            catch (Exception ex)
            {
                if (document != null)
                {
                    document.Close();
                }
                if (pdfStamper != null)
                {
                    pdfStamper.Close();
                }
                throw ex;
            }
        }
        //ia semnatura de al serviciu si o baga in fisier
        private void EmbededHashInPDF(byte[] pk, string idFile)
        {
            //return ms.ToArray();
            using (SPSite site = new SPSite("http://*****:*****@"C:\PDF\out.pdf", ms.ToArray());

                        selectedItem.File.ParentFolder.Files.Add(selectedItem.Name, ms.ToArray(), true);
                        //SPListItem currentFile = listFiles.GetItemById(Int32.Parse(publicFileID));
                    }
                    catch (Exception e)
                    {
                    }
                }
            }
        }
        /**
         * Signs the document using the detached mode, CMS or CAdES equivalent.
         * @param sap the PdfSignatureAppearance
         * @param externalSignature the interface providing the actual signing
         * @param chain the certificate chain
         * @param crlList the CRL list
         * @param ocspClient the OCSP client
         * @param tsaClient the Timestamp client
         * @param provider the provider or null
         * @param estimatedSize the reserved size for the signature. It will be estimated if 0
         * @param cades true to sign CAdES equivalent PAdES-BES, false to sign CMS
         * @throws DocumentException
         * @throws IOException
         * @throws GeneralSecurityException
         * @throws NoSuchAlgorithmException
         * @throws Exception
         */
        public static void SignDetached(PdfSignatureAppearance sap, IExternalSignature externalSignature, ICollection <X509Certificate> chain, ICollection <ICrlClient> crlList, IOcspClient ocspClient,
                                        ITSAClient tsaClient, int estimatedSize, CryptoStandard sigtype)
        {
            List <X509Certificate> certa    = new List <X509Certificate>(chain);
            ICollection <byte[]>   crlBytes = null;
            int i = 0;

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

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

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

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

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

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

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

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

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

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

            PdfDictionary dic2 = new PdfDictionary();

            dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true));
            sap.Close(dic2);
        }
Esempio n. 13
0
        public byte[] SignDetached(byte[] data, int certIndex, string storeLocation, string storeName, string location, string reason, int position)
        {
            MemoryStream outMs = new MemoryStream();
            // X509Certificate2 card = GetCertificate(certIndex, storeLocation, storeName);
            // FAILLACE qui tocca fornire il certificato?
            X509Certificate2 card = null;

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

            PdfReader  reader  = new PdfReader(data);
            PdfStamper stp     = null;
            bool       isPades = IsPdfPades(reader);
            bool       isPdfA  = IsPDFA(reader);

            if (isPades)  //se pades vado in append.
            {
                stp = PdfStamper.CreateSignature(reader, outMs, '\0', null, true);
            }
            else
            {
                stp = PdfStamper.CreateSignature(reader, outMs, '\0');
            }

            if (isPdfA)
            {
                stp.Writer.PDFXConformance = PdfWriter.PDFA1A;
            }


            PdfSignatureAppearance sap = stp.SignatureAppearance;
            Rectangle pageSize         = reader.GetPageSize(1);
            Rectangle signatureRect    = setPosition(position, pageSize);

            sap.SetVisibleSignature(signatureRect, 1, null);
            sap.SignDate = DateTime.Now;
            sap.SetCrypto(null, chain, null, null);
            sap.Reason      = reason;
            sap.Location    = location;
            sap.Acro6Layers = true;
            sap.Render      = PdfSignatureAppearance.SignatureRender.NameAndDescription;

            //così appare solo il testo che voglio io.
            sap.Layer2Text = "Test";
            sap.Render     = PdfSignatureAppearance.SignatureRender.Description;

            if (isPdfA)
            {
                //BaseFont bf = BaseFont.CreateFont(@"c:\windows\fonts\arial.ttf", BaseFont.WINANSI, true);
                //forse va sistemato questo path.
                Stream fo = BaseFont.GetResourceStream("DPA.DigitalSignature.Itextsharp.iTextSharp.text.pdf.fonts.Helvetica.afm");

                byte[] fb = new BinaryReader(fo).ReadBytes((int)fo.Length);
                //BaseFont bf1 = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, true);
                BaseFont bf = BaseFont.CreateFont("helvetica.afm", BaseFont.WINANSI, true, false, fb, fb);

                sap.Layer2Font = new Font(bf);
            }

            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;
            }
            sap.CryptoDictionary = dic;
            int csize = 10000;
            Dictionary <PdfName, int> exc = new Dictionary <PdfName, int>();

            exc[PdfName.CONTENTS] = csize * 2 + 2;
            Hashtable dict_hasht = new Hashtable(exc);

            sap.PreClose(dict_hasht);

            Stream       s    = sap.RangeStream;
            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);
            }

            byte[] pk = FirmaFileBouncy(ss.ToArray(), card);
            //pk = SignMsg(ss.ToArray(), card, true);

            byte[] outc = new byte[csize];

            PdfDictionary dic2 = new PdfDictionary();

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

            dic2.Put(PdfName.CONTENTS, new PdfString(outc).SetHexWriting(true));
            sap.Close(dic2, true);
            outMs.Position = 0;
            BinaryReader br = new BinaryReader(outMs);

            byte[] retval = br.ReadBytes((int)outMs.Length);
            outMs.Close();
            return(retval);
        }
Esempio n. 14
0
        /// <summary>
        /// Predisone un file Pades alla firma, se il parametro signature è vuoto torna l'hash del file da firmare, se è pieno lo firma
        /// </summary>
        /// <param name="data">i dati del PDF</param>
        /// <param name="signature">i dati della firma, se null calcola solo l'hash</param>
        /// <returns></returns>
        public static byte[] SignPadesFile(byte[] data, byte[] signature)
        {
            MemoryStream outMs = new MemoryStream();

            PdfReader  reader  = new PdfReader(data);
            PdfStamper stp     = null;
            bool       isPades = true;
            //bool isPades = IsPdfPades(reader);
            bool isPdfA = IsPDFA(reader);

            if (isPades)  //se pades vado in append.
            {
                stp = PdfStamper.CreateSignature(reader, outMs, '\0', null, true);
            }
            else
            {
                stp = PdfStamper.CreateSignature(reader, outMs, '\0');
            }

            if (isPdfA)
            {
                stp.Writer.PDFXConformance = PdfWriter.PDFA1A;
            }


            PdfSignatureAppearance sap = stp.SignatureAppearance;

            if (isPdfA)
            {
                //BaseFont bf = BaseFont.CreateFont(@"c:\windows\fonts\arial.ttf", BaseFont.WINANSI, true);
                //forse va sistemato questo path.
                //Pades_Utils.dpaItextSharp.iTextSharp.text.pdf.fonts.Helvetica.afm
                //DPA.DigitalSignature.Itextsharp.iTextSharp.text.pdf.fonts.Helvetica.afm
                Stream   fo = BaseFont.GetResourceStream("Pades_Utils.dpaItextSharp.iTextSharp.text.pdf.fonts.Helvetica.afm");
                byte[]   fb = new BinaryReader(fo).ReadBytes((int)fo.Length);
                BaseFont bf = BaseFont.CreateFont("helvetica.afm", BaseFont.WINANSI, true, false, fb, fb);
                sap.Layer2Font = new Font(bf);
                //BaseFont bf1 = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, true);

                // bf = BaseFont.CreateFont (
            }

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

            sap.CryptoDictionary = dic;

            //generazione nuovo pdf
            int csize = 10000;
            Dictionary <PdfName, int> exc = new Dictionary <PdfName, int>();

            exc[PdfName.CONTENTS] = csize * 2 + 2;
            Hashtable dic_hasht = new Hashtable(exc);

            sap.PreClose(dic_hasht);

            /*
             * //tolgo l'id
             * stp.Reader.Trailer.Put(dpaItextSharp.text.pdf.PdfName.ID, null);
             * dpaItextSharp.text.pdf.PdfDictionary dict = (dpaItextSharp.text.pdf.PdfDictionary)stp.Reader.Trailer.GetAsDict(dpaItextSharp.text.pdf.PdfName.INFO);
             * dict.Put(dpaItextSharp.text.pdf.PdfName.MODDATE, null);
             * stp.Writer.Info.Put(dpaItextSharp.text.pdf.PdfName.MODDATE, null);
             */

            Stream       s    = sap.RangeStream;
            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);
            }


            //se signature è vuota a me interessa SOLO l'hash sha256 e lo ritorno
            if (signature == null)
            {
                return(PKCS_Utils.Pkcs.getSha256(ss.ToArray()));
            }

            // ho una firma, procedo con l'append della firma sul file.
            byte[] outc = new byte[csize];

            PdfDictionary dic2 = new PdfDictionary();

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

            dic2.Put(PdfName.CONTENTS, new PdfString(outc).SetHexWriting(true));
            sap.Close(dic2, true);
            outMs.Position = 0;
            BinaryReader br = new BinaryReader(outMs);

            byte[] retval = br.ReadBytes((int)outMs.Length);
            outMs.Close();
            return(retval);
        }
Esempio n. 15
0
        private static void DoSignPdfFile(PdfStamper stamper, ConversionProfile profile, JobPasswords jobPasswords)
        {
            Signature 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;

            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 (!string.IsNullOrEmpty(signing.TimeServerUrl.Trim()))
            {
                if (!signing.TimeServerIsSecured)
                {
                    tsc = new TSAClientBouncyCastle(signing.TimeServerUrl);
                }
                else
                {
                    tsc = new TSAClientBouncyCastle(signing.TimeServerUrl, signing.TimeServerLoginName, signing.TimeServerPassword);
                }
            }

            PdfSignatureAppearance 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 PDFCreator)
                psa.CertificationLevel = PdfSignatureAppearance.CERTIFIED_FORM_FILLING_AND_ANNOTATIONS;
            }

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

            if (signing.DisplaySignatureInDocument)
            {
                int 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);
            IDigest      messageDigest = DigestUtilities.GetDigest(hashAlgorithm);
            Stream       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)
            {
                String url = PdfPKCS7.GetOCSPURL(chain[0]);
                if (!string.IsNullOrEmpty(url))
                {
                    ocsp = new OcspClientBouncyCastle().GetEncoded(chain[0], chain[1], url);
                }
            }
            DateTime cal = psa.SignDate;

            byte[] 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
            {
                byte[] encodedSig = sgn.GetEncodedPKCS7(hash, cal);
                Array.Copy(encodedSig, 0, paddedSig, 0, encodedSig.Length);
                if (contentEstimated + 2 < encodedSig.Length)
                {
                    throw new ProcessingException("Not enough space for signature", 12203);
                }
            }

            var dic2 = new PdfDictionary();

            dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true));
            psa.Close(dic2);
        }
Esempio n. 16
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();
        }
Esempio n. 17
0
        /// <summary>
        /// Configura la informacion del certificado digital
        /// </summary>
        /// <param name="origen"></param>
        /// <param name="destino"></param>
        /// <param name="rutaCertificado"></param>
        /// <param name="pass"></param>
        public bool infoCertificado(string origen, string destino, string rutaCertificado, string pass)
        {
            bool resultado = false;

            try
            {
                //SAPbouiCOM.Framework.Application.SBO_Application.MessageBox("origen " + origen);
                //SAPbouiCOM.Framework.Application.SBO_Application.MessageBox("destino " + destino);
                //SAPbouiCOM.Framework.Application.SBO_Application.MessageBox("rutaCertificado " + rutaCertificado);
                //SAPbouiCOM.Framework.Application.SBO_Application.MessageBox("clave " + pass);

                //Se obtiene el certficado
                x509.X509Certificate2 certificado = new x509.X509Certificate2(rutaCertificado, pass);
                X509CertificateParser objCP       = new X509CertificateParser();

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

                //Objeto de tipo documento pdf
                PdfReader objReader = new PdfReader(origen);
                //Crea el objeto para la firma digital
                PdfStamper objStamper = PdfStamper.CreateSignature(objReader,
                                                                   new FileStream(destino, FileMode.Create), '\0');
                PdfSignatureAppearance objSA = objStamper.SignatureAppearance;

                //Configuracion de informacion para la firma digital
                objSA.SignDate = DateTime.Now;
                objSA.SetCrypto(null, objChain, null, null);
                objSA.Reason      = "Comprobante Generado";
                objSA.Location    = "Uruguay";
                objSA.Acro6Layers = true;
                objSA.Render      = PdfSignatureAppearance.SignatureRender.NameAndDescription;

                PdfSignature objSignature = new PdfSignature(PdfName.ADOBE_PPKMS,
                                                             PdfName.ADBE_PKCS7_SHA1);
                objSignature.Date = new PdfDate(objSA.SignDate);
                objSignature.Name = PdfPKCS7.GetSubjectFields(objChain[0]).GetField("CN");

                if (objSA.Reason != null)
                {
                    objSignature.Reason = objSA.Reason;
                }

                if (objSA.Location != null)
                {
                    objSignature.Location = objSA.Location;
                }

                objSA.CryptoDictionary = objSignature;
                int intCSize = 4000;

                Hashtable objTable = new Hashtable();
                objTable[PdfName.CONTENTS] = intCSize * 2 + 2;
                objSA.PreClose(objTable);
                Stream objStream = objSA.RangeStream;

                HashAlgorithm objSHA1 = new SHA1CryptoServiceProvider();
                int           intRead = 0;

                byte[] bytBuffer = new byte[8192];
                while ((intRead = objStream.Read(bytBuffer, 0, 8192)) > 0)
                {
                    objSHA1.TransformBlock(bytBuffer, 0, intRead, bytBuffer, 0);
                }
                objSHA1.TransformFinalBlock(bytBuffer, 0, 0);

                byte[] bytPK  = firmarDocumento(objSHA1.Hash, certificado);
                byte[] bytOut = new byte[intCSize];

                PdfDictionary objDict = new PdfDictionary();
                Array.Copy(bytPK, 0, bytOut, 0, bytPK.Length);

                objDict.Put(PdfName.CONTENTS, new PdfString(bytOut).SetHexWriting(true));
                objStream.Close();
                objSA.Close(objDict);
                resultado = true;
            }
            catch (Exception ex)
            {
                SAPbouiCOM.Framework.Application.SBO_Application.MessageBox("ERROR: " + ex.ToString());
            }

            return(resultado);
        }
Esempio n. 18
0
        public static int Main(string[] args)
        {
            // Разбираем аргументы
            if (args.Length < 2)
            {
                Console.WriteLine("Pdf.Sign <document> <certificate-dn> [<key-container-password>]");
                return(1);
            }
            string document       = args[0];
            string certificate_dn = args[1];

            /*
             * // Извлечение клиентского сертификата из хранилища:
             * X509Store x509Store = new X509Store(StoreLocation.CurrentUser);
             * x509Store.Open(OpenFlags.ReadOnly);
             * var x509Certificate = x509Store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName,
             *  //"[email protected], CN=Sozonjuk Aleksandr Vasil'evich, OU=Department of information technologies, O=s3bank.ru, L=Moscow, S=Moscow, C=RU",
             *  "[email protected], CN=S3Bank-Rostelecom Service, OU=IT Department, O=s3bank.ru, L=Moscow, S=Moscow, C=RU",
             *  false)[0];
             */

            // Находим секретный ключ по сертификату в хранилище
            X509Store x509Store = new X509Store("My", StoreLocation.CurrentUser);

            x509Store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
            X509Certificate2Collection found = x509Store.Certificates.Find(
                //X509FindType.FindByThumbprint, certificate_dn, true);
                X509FindType.FindBySubjectDistinguishedName, certificate_dn, true);

            if (found.Count == 0)
            {
                Console.WriteLine("Секретный ключ не найден.");
                return(1);
            }
            if (found.Count > 1)
            {
                Console.WriteLine("Найдено более одного секретного ключа.");
                return(1);
            }
            X509Certificate2 certificate = found[0];

            if (args.Length > 2)
            {
                //set password. Пароль "0"
                //var cert_key = certificate.PrivateKey as Gost3410_2012_256CryptoServiceProvider; //Gost3410CryptoServiceProvider;
                var cert_key = certificate.PrivateKey as Gost3410CryptoServiceProvider;
                if (null != cert_key)
                {
                    var cspParameters = new CspParameters();
                    //копируем параметры csp из исходного контекста сертификата
                    cspParameters.KeyContainerName = cert_key.CspKeyContainerInfo.KeyContainerName;
                    cspParameters.ProviderType     = cert_key.CspKeyContainerInfo.ProviderType;
                    cspParameters.ProviderName     = cert_key.CspKeyContainerInfo.ProviderName;
                    cspParameters.Flags            = cert_key.CspKeyContainerInfo.MachineKeyStore
                                      ? (CspProviderFlags.UseExistingKey | CspProviderFlags.UseMachineKeyStore)
                                      : (CspProviderFlags.UseExistingKey);
                    cspParameters.KeyPassword = new SecureString();
                    foreach (var c in args[2])
                    {
                        cspParameters.KeyPassword.AppendChar(c);
                    }
                    //создаем новый контекст сертификат, поскольку исходный открыт readonly
                    certificate = new X509Certificate2(certificate.RawData);

                    //задаем криптопровайдер с установленным паролем
                    //certificate.PrivateKey = new Gost3410_2012_256CryptoServiceProvider(cspParameters);
                    certificate.PrivateKey = new Gost3410CryptoServiceProvider(cspParameters);
                }
            }

            PdfReader              reader = new PdfReader(document);
            PdfStamper             st     = PdfStamper.CreateSignature(reader, new FileStream(document.Replace(".pdf", "") + "_signed.pdf", FileMode.Create, FileAccess.Write), '\0');
            PdfSignatureAppearance sap    = st.SignatureAppearance;

            // Загружаем сертификат в объект iTextSharp
            X509CertificateParser parser = new X509CertificateParser();

            Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] {
                parser.ReadCertificate(certificate.RawData)
            };

            sap.Certificate = parser.ReadCertificate(certificate.RawData);
            sap.Reason      = "Первый сценарий";
            sap.Location    = "Universe";
            sap.Acro6Layers = true;

            //sap.Render = PdfSignatureAppearance.SignatureRender.NameAndDescription;
            sap.SignDate = DateTime.Now;

            // Выбираем подходящий тип фильтра
            PdfName filterName = new PdfName("CryptoPro PDF");

            // Создаем подпись
            PdfSignature dic = new PdfSignature(filterName, PdfName.ADBE_PKCS7_DETACHED);

            dic.Date = new PdfDate(sap.SignDate);
            dic.Name = "PdfPKCS7 signature";
            if (sap.Reason != null)
            {
                dic.Reason = sap.Reason;
            }
            if (sap.Location != null)
            {
                dic.Location = sap.Location;
            }
            sap.CryptoDictionary = dic;

            int intCSize = 4000;
            Dictionary <PdfName, int> hashtable = new Dictionary <PdfName, int>();

            hashtable[PdfName.CONTENTS] = intCSize * 2 + 2;
            sap.PreClose(hashtable);
            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);
            }

            // Вычисляем подпись
            ContentInfo contentInfo = new ContentInfo(ss.ToArray());
            SignedCms   signedCms   = new SignedCms(contentInfo, true);
            CmsSigner   cmsSigner   = new CmsSigner(certificate);

            signedCms.ComputeSignature(cmsSigner, false);
            byte[] pk = signedCms.Encode();

            // Помещаем подпись в документ
            byte[]        outc = new byte[intCSize];
            PdfDictionary dic2 = new PdfDictionary();

            Array.Copy(pk, 0, outc, 0, pk.Length);
            dic2.Put(PdfName.CONTENTS, new PdfString(outc).SetHexWriting(true));
            sap.Close(dic2);

            Console.WriteLine("Документ {0} успешно подписан на ключе {1} => {2}.",
                              document, certificate.Subject, document + "_signed.pdf");
            return(0);
        }
Esempio n. 19
0
        public override byte[] Sign(byte[] pdf, bool detached)
        {
            if (_certificate == null)
            {
                _certificate = GetCertificate();

                if (_certificate == null)
                {
                    throw new Exceptions.CertificateNotFoundException(this.CertificateSelector);
                }

                _chain = GetChain();
            }

            PdfReader reader = new PdfReader(pdf);

            using (MemoryStream result = new MemoryStream())
            {
                PdfStamper             stp = PdfStamper.CreateSignature(reader, result, '\0');
                PdfSignatureAppearance sap = stp.SignatureAppearance;

                sap.SetCrypto(null, _chain, null, null);

                this.OnPrepareSignatureEvent(
                    new CertificateInfo
                {
                    CN           = PdfPKCS7.GetSubjectFields(_chain[0]).GetField("CN"),
                    SerialNumber = PdfPKCS7.GetSubjectFields(_chain[0]).GetField("SN")
                }
                    , sap);

                this.PrepareAppareance(sap);

                PdfSignature dic = null;

                if (detached)
                {
                    dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
                }
                else
                {
                    dic = new PdfSignature(PdfName.ADOBE_PPKMS, PdfName.ADBE_PKCS7_SHA1);
                }

                dic.Date = new PdfDate(sap.SignDate);
                dic.Name = PdfPKCS7.GetSubjectFields(_chain[0]).GetField("CN");

                this.PrepareSignature(dic, sap);

                sap.CryptoDictionary = dic;

                int       csize = detached ? 10000 : 4000;
                Hashtable exc   = new Hashtable();
                exc[PdfName.CONTENTS] = csize * 2 + 2;
                sap.PreClose(exc);

                byte[] msg = null;
                if (detached)
                {
                    msg = GetMsgDetached(sap);
                }
                else
                {
                    msg = GetMsgHashed(sap);
                }

                byte[] pk = SignMsg(msg, _certificate, detached);

                byte[] outc = new byte[csize];

                PdfDictionary dic2 = new PdfDictionary();

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

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

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

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

            Dictionary<PdfName,int> exc = new Dictionary<PdfName,int>();
            exc[PdfName.CONTENTS] = contentEstimated * 2 + 2;
            sap.PreClose(exc);
            Stream data = sap.GetRangeStream();
            IDigest messageDigest = tsa.GetMessageDigest();
            byte[] buf = new byte[4096];
            int n;
            while ((n = data.Read(buf, 0, buf.Length)) > 0) {
                messageDigest.BlockUpdate(buf, 0, n);
            }
            byte[] tsImprint = new byte[messageDigest.GetDigestSize()];
            messageDigest.DoFinal(tsImprint, 0);
            byte[] tsToken;
            try {
        	    tsToken = tsa.GetTimeStampToken(tsImprint);
            }
            catch(Exception e) {
        	    throw new GeneralSecurityException(e.Message);
            }
            if (contentEstimated + 2 < tsToken.Length)
                throw new IOException("Not enough space");

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

            PdfDictionary dic2 = new PdfDictionary();
            dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true));
            sap.Close(dic2);
        }
Esempio n. 21
0
        public bool FirmarPDF(string pdfOriginal, string pdfFirmado, SysX509.X509Certificate2 certificado, string imagenFirma, bool firmaVisible, float puntoEsquinaInferiorIzquierdaX, float puntoEsquinaInferiorIzquierdaY, float puntoEsquinaSuperiorDerechaX, float puntoEsquinaSuperiorDerechaY, eTipoPagina paginaFirma, int pagina)
        {
            int numPagina = 0;

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

                PdfReader              objReader  = new PdfReader(pdfOriginal);
                PdfStamper             objStamper = PdfStamper.CreateSignature(objReader, new FileStream(pdfFirmado, FileMode.Create), '\0');
                PdfSignatureAppearance objSA      = objStamper.SignatureAppearance;

                if (paginaFirma == eTipoPagina.Ultima)
                {
                    numPagina = objReader.NumberOfPages;
                }
                else
                {
                    if (pagina <= objReader.NumberOfPages)
                    {
                        numPagina = pagina;
                    }
                    else if (pagina > objReader.NumberOfPages)
                    {
                        numPagina = objReader.NumberOfPages;
                    }
                    else if (pagina < 1)
                    {
                        numPagina = 1;
                    }
                }
                if (firmaVisible)
                {
                    Rectangle rect = new Rectangle(puntoEsquinaInferiorIzquierdaX, puntoEsquinaInferiorIzquierdaY, puntoEsquinaSuperiorDerechaX, puntoEsquinaSuperiorDerechaY);
                    objSA.SetVisibleSignature(rect, numPagina, null);
                }


                objSA.CertificationLevel = PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED;

                objSA.SignDate = DateTime.Now;
                objSA.SetCrypto(null, objChain, null, null);
                objSA.Acro6Layers = true;
                objSA.Render      = PdfSignatureAppearance.SignatureRender.NameAndDescription;
                //objSA.SignatureGraphic = iTextSharp.text.Image.GetInstance(imagenFirma); //
                PdfSignature objSignature = new PdfSignature(PdfName.ADOBE_PPKMS, PdfName.ADBE_PKCS7_SHA1);
                objSignature.Date = new PdfDate(objSA.SignDate);
                objSignature.Name = PdfPKCS7.GetSubjectFields(objChain[0]).GetField("CN");
                if (objSA.Reason != null)
                {
                    objSignature.Reason = objSA.Reason;
                }
                if (objSA.Location != null)
                {
                    objSignature.Location = objSA.Location;
                }
                if (objSA.Contact != null)
                {
                    objSignature.Contact = objSA.Contact;
                }
                objSA.CryptoDictionary = objSignature;
                int intCSize = 4000;
                Dictionary <PdfName, int> objTable = new Dictionary <PdfName, int>();
                objTable[PdfName.CONTENTS] = intCSize * 2 + 2;
                objSA.PreClose(objTable);

                HashAlgorithm objSHA1 = new SHA1CryptoServiceProvider();

                Stream objStream = objSA.RangeStream;
                int    intRead   = 0;
                byte[] bytBuffer = new byte[8192];
                while ((intRead = objStream.Read(bytBuffer, 0, 8192)) > 0)
                {
                    objSHA1.TransformBlock(bytBuffer, 0, intRead, bytBuffer, 0);
                }
                objSHA1.TransformFinalBlock(bytBuffer, 0, 0);

                byte[] bytPK  = GenerarFirmar(objSHA1.Hash, certificado, false);
                byte[] bytOut = new byte[intCSize];

                PdfDictionary objDict = new PdfDictionary();

                Array.Copy(bytPK, 0, bytOut, 0, bytPK.Length);

                objDict.Put(PdfName.CONTENTS, new PdfString(bytOut).SetHexWriting(true));
                objSA.Close(objDict);

                return(true);
            }
            catch
            {
                throw;
            }
        }
Esempio n. 22
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);
        }
Esempio n. 23
0
        public bool Sign(string iSignReason, string iSignContact, string iSignLocation, bool visible, string iImageString)
        {
            string vCertificatesPath = "CN=" + CertificatesName;

            #region Geting Certs

            X509Store       store = new X509Store(_storedName, _storedLocation);
            StorePermission sp    = new StorePermission(PermissionState.Unrestricted);
            sp.Flags = StorePermissionFlags.OpenStore;
            sp.Assert();
            store.Open(OpenFlags.MaxAllowed);
            X509Certificate2 cert = null;
            int i = 0;
            while ((i < store.Certificates.Count) && (cert == null))
            {
                if (store.Certificates[i].Subject.ToUpper().Contains(vCertificatesPath))
                {
                    cert = store.Certificates[i];
                }
                else
                {
                    i++;
                }
            }
            store.Close();
            if (cert == null)
            {
                throw new CryptographicException("Certificate is NULL. Certificate can not be found");
            }
            Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser();
            var cerRawData   = cert.RawData;
            var certificates = cp.ReadCertificate(cerRawData);
            Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { certificates };

            var chainFirst = GetChainBouncyCastle(cert);

            #endregion Geting Certs

            PdfReader reader = null;
            if (string.IsNullOrEmpty(inputPdfFileString))
            {
                reader = new PdfReader(inputPdfStream);
            }
            else
            {
                reader = new PdfReader(this.inputPdfFileString);
            }
            if (outputPdfStream == null && string.IsNullOrEmpty(outputPdfFileString) == false)
            {
                outputPdfStream = new FileStream(this.outputPdfFileString, FileMode.OpenOrCreate, FileAccess.Write);
            }
            if (reader != null && outputPdfStream != null)
            {
                #region Standard Signing

                PdfStamper vStamper = PdfStamper.CreateSignature(reader, outputPdfStream, '\0', null, false);
                vStamper.MoreInfo    = this.settingMetadata.GetMetaDataHashtable();
                vStamper.XmpMetadata = this.settingMetadata.GetStreamedMetaData();

                PdfSignatureAppearance vSignatureAppearance = vStamper.SignatureAppearance;
                vSignatureAppearance.SetCrypto(null, chain, null, PdfSignatureAppearance.SELF_SIGNED);
                vSignatureAppearance.SignDate    = SignDate;
                vSignatureAppearance.Reason      = iSignReason;
                vSignatureAppearance.Contact     = iSignContact;
                vSignatureAppearance.Location    = iSignLocation;
                vSignatureAppearance.Acro6Layers = true;
                vSignatureAppearance.Render      = PdfSignatureAppearance.SignatureRender.Description;
                if (visible)
                {
                    vSignatureAppearance.SetVisibleSignature(
                        new iTextSharp.text.Rectangle(ImageLocation.Width, ImageLocation.Height, ImageLocation.Width + ImageSize.Width, ImageLocation.Height + ImageSize.Height),
                        1, null);
                    if (File.Exists(iImageString))
                    {
                        iTextSharp.text.Image vImage = iTextSharp.text.Image.GetInstance(iImageString);
                        vSignatureAppearance.Image = vImage;
                    }
                }
                vSignatureAppearance.SetExternalDigest(new byte[128], new byte[20], "RSA");

                #endregion Standard Signing

                #region Self Signed Mode

                PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKMS, PdfName.ADBE_PKCS7_SHA1);
                dic.Date = new PdfDate(vSignatureAppearance.SignDate);
                var vName = PdfPKCS7.GetSubjectFields(chain[0]).GetField("CN");
                dic.Name = vName;
                if (vSignatureAppearance.Reason != null)
                {
                    dic.Reason = vSignatureAppearance.Reason;
                }
                if (vSignatureAppearance.Location != null)
                {
                    dic.Location = vSignatureAppearance.Location;
                }
                vSignatureAppearance.CryptoDictionary = dic;

                int csize = 4000;
                Dictionary <PdfName, int> exc = new Dictionary <PdfName, int>();
                exc[PdfName.CONTENTS] = csize * 2 + 2;
                vSignatureAppearance.PreClose(new Hashtable(exc));

                HashAlgorithm sha = new SHA1CryptoServiceProvider();

                Stream s    = vSignatureAppearance.RangeStream;
                int    read = 0;
                byte[] buff = new byte[8192];
                while ((read = s.Read(buff, 0, 8192)) > 0)
                {
                    sha.TransformBlock(buff, 0, read, buff, 0);
                }
                sha.TransformFinalBlock(buff, 0, 0);
                byte[]        pk   = SignMsg(sha.Hash, cert, false);
                byte[]        outc = new byte[csize];
                PdfDictionary dic2 = new PdfDictionary();
                Array.Copy(pk, 0, outc, 0, pk.Length);
                dic2.Put(PdfName.CONTENTS, new PdfString(outc).SetHexWriting(true));
                vSignatureAppearance.Close(dic2);

                #endregion Self Signed Mode

                if (vSignatureAppearance.IsPreClosed() == false)
                {
                    vStamper.Close();
                }
                reader.Close();
                return(true);
            }
            return(false);
        }
Esempio n. 24
0
        /// <summary>
        /// Firma un documento
        /// </summary>
        /// <param name="Source">Documento origen</param>
        /// <param name="Target">Documento destino</param>
        /// <param name="Certificate">Certificado a utilizar</param>
        /// <param name="Reason">Razón de la firma</param>
        /// <param name="Location">Ubicación</param>
        /// <param name="AddVisibleSign">Establece si hay que agregar la firma visible al documento</param>
        public void SignHashed(string Source, string Target, SysX509.X509Certificate2 Certificate, string Reason, string Location, bool AddVisibleSign, DatosPersonales datos)
        {
            X509CertificateParser objCP = new X509CertificateParser();

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

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

            if (AddVisibleSign)
            {
                objSA.SetVisibleSignature(new Rectangle(100f, objReader.XrefSize, 500, 100), 1, null);
            }

            objSA.SignDate = DateTime.Now;
            objSA.SetCrypto(null, objChain, null, null);
            objSA.Reason      = Reason;
            objSA.Location    = Location;
            objSA.Acro6Layers = true;
            objSA.Render      = PdfSignatureAppearance.SignatureRender.NameAndDescription;
            PdfSignature objSignature = new PdfSignature(PdfName.ADOBE_PPKMS, PdfName.ADBE_PKCS7_SHA1);

            objSignature.Date = new PdfDate(objSA.SignDate);
            objSignature.Name = PdfPKCS7.GetSubjectFields(objChain[0]).GetField("CN");
            if (objSA.Reason != null)
            {
                objSignature.Reason = objSA.Reason;
            }
            if (objSA.Location != null)
            {
                objSignature.Location = objSA.Location;
            }
            objSA.CryptoDictionary = objSignature;
            int intCSize = 4000;


            //  Hashtable objTable = new Hashtable();
            //  objTable[PdfName.CONTENTS] = intCSize * 2 + 2;
            Dictionary <PdfName, int> objTable = new Dictionary <PdfName, int>();
            PdfName pdfname = new PdfName("firma");

            // Add some elements to the dictionary. There are no
            // duplicate keys, but some of the values are duplicates.
            objTable.Add(pdfname, intCSize * 2 + 2);
            objSA.PreClose(objTable);

            HashAlgorithm objSHA1 = new SHA1CryptoServiceProvider();

            Stream objStream = objSA.RangeStream;
            int    intRead   = 0;

            byte[] bytBuffer = new byte[8192];
            while ((intRead = objStream.Read(bytBuffer, 0, 8192)) > 0)
            {
                objSHA1.TransformBlock(bytBuffer, 0, intRead, bytBuffer, 0);
            }
            objSHA1.TransformFinalBlock(bytBuffer, 0, 0);

            byte[] bytPK  = SignMsg(objSHA1.Hash, Certificate, false);
            byte[] bytOut = new byte[intCSize];

            PdfDictionary objDict = new PdfDictionary();

            Array.Copy(bytPK, 0, bytOut, 0, bytPK.Length);

            objDict.Put(pdfname, new PdfString(bytOut).SetHexWriting(true));
            try
            {
                objSA.Close(objDict);
            }
            catch (Exception ex)
            {
            }
        }
        /**
         * Sign the document using an external container, usually a PKCS7. The signature is fully composed
         * externally, iText will just put the container inside the document.
         * @param sap the PdfSignatureAppearance
         * @param externalSignatureContainer the interface providing the actual signing
         * @param estimatedSize the reserved size for the signature
         * @throws GeneralSecurityException
         * @throws IOException
         * @throws DocumentException 
         */
        public static void SignExternalContainer(PdfSignatureAppearance sap, IExternalSignatureContainer externalSignatureContainer, int estimatedSize) {
            PdfSignature dic = new PdfSignature(null, null);
            dic.Reason = sap.Reason;
            dic.Location = sap.Location;
            dic.SignatureCreator = sap.SignatureCreator;
            dic.Contact = sap.Contact;
            dic.Date = new PdfDate(sap.SignDate); // time-stamp will over-rule this
            externalSignatureContainer.ModifySigningDictionary(dic);
            sap.CryptoDictionary = dic;

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

            Stream data = sap.GetRangeStream();
            byte[] encodedSig = externalSignatureContainer.Sign(data);

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

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

            PdfDictionary dic2 = new PdfDictionary();
            dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true));
            sap.Close(dic2);
        }
Esempio n. 26
0
        static void signPDF(string document)
        {
            //string certificate_dn = "C=RU, S=lenobl, L=spb, O=fil, OU=IT, CN=iks, E=iks@iks";  // Subject->Name

            string certificate_dn = "L=Санкт-Петербург, O=ООО Филберт, CN=iks, [email protected]";



            X509Store store = new X509Store("My", StoreLocation.CurrentUser);

            store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
            X509Certificate2Collection found = store.Certificates.Find(
                X509FindType.FindBySubjectDistinguishedName, certificate_dn, true);


            if (found.Count == 0)
            {
                Console.Out.Write("Сертфикат [" + certificate_dn + "] не найден ");
                return;
            }

            if (found.Count > 1)
            {
                Console.WriteLine("Найдено более одного секретного ключа.");
                return;
            }



            X509Certificate2 certificate = found[0];

            CryptoPro.Sharpei.Gost3410_2012_256CryptoServiceProvider cert_key = certificate.PrivateKey as CryptoPro.Sharpei.Gost3410_2012_256CryptoServiceProvider;


            var cspParameters = new CspParameters();

            //копируем параметры csp из исходного контекста сертификата
            cspParameters.KeyContainerName = cert_key.CspKeyContainerInfo.KeyContainerName;
            cspParameters.ProviderType     = cert_key.CspKeyContainerInfo.ProviderType;
            cspParameters.ProviderName     = cert_key.CspKeyContainerInfo.ProviderName;
            cspParameters.Flags            = cert_key.CspKeyContainerInfo.MachineKeyStore
                              ? (CspProviderFlags.UseExistingKey | CspProviderFlags.UseMachineKeyStore)
                              : (CspProviderFlags.UseExistingKey);
            cspParameters.KeyPassword = new SecureString();
            string pass = "******";

            foreach (var c in pass)
            {
                cspParameters.KeyPassword.AppendChar(c);
            }
            //создаем новый контекст сертификат, поскольку исходный открыт readonly
            certificate = new X509Certificate2(certificate.RawData);
            //задаем криптопровайдер с установленным паролем
            certificate.PrivateKey = new CryptoPro.Sharpei.Gost3410_2012_256CryptoServiceProvider(cspParameters);


            /////////////////////////читаем файл

            /*
             *          System.IO.StreamReader file = new System.IO.StreamReader("C:\\TEMP\\test.json");
             *
             *          string s = file.ReadToEnd();
             *                byte[] body = Encoding.Default.GetBytes(s);
             */


            /////////////////////////////   PDF  подпись ////////////////////////////////////////////////

            PdfReader reader = new PdfReader(document);


            string newSigned = Path.Combine(Path.GetDirectoryName(document) + @"\" + Path.GetFileNameWithoutExtension(document) + "_signed" + Path.GetExtension(document));

            FileStream             signedPDF = new FileStream(newSigned, FileMode.Create, FileAccess.ReadWrite);
            PdfStamper             st        = PdfStamper.CreateSignature(reader, signedPDF, '\0', null, true);
            PdfSignatureAppearance sap       = st.SignatureAppearance;



            // Загружаем сертификат в объект iTextSharp
            X509CertificateParser parser = new X509CertificateParser();

            Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] {
                parser.ReadCertificate(certificate.RawData)
            };

            sap.Certificate = parser.ReadCertificate(certificate.RawData);
            sap.Reason      = "I like to sign";
            sap.Location    = "Universe";
            sap.Acro6Layers = true;

            //sap.Render = PdfSignatureAppearance.SignatureRender.NameAndDescription;
            sap.SignDate = DateTime.Now;

            // Выбираем подходящий тип фильтра
            PdfName filterName = new PdfName("CryptoPro PDF");

            // Создаем подпись
            PdfSignature dic = new PdfSignature(filterName, PdfName.ADBE_PKCS7_DETACHED);

            dic.Date = new PdfDate(sap.SignDate);
            dic.Name = "iks";
            if (sap.Reason != null)
            {
                dic.Reason = sap.Reason;
            }
            if (sap.Location != null)
            {
                dic.Location = sap.Location;
            }
            sap.CryptoDictionary = dic;

            int intCSize = 4000;
            Dictionary <PdfName, int> hashtable = new Dictionary <PdfName, int>();

            hashtable[PdfName.CONTENTS] = intCSize * 2 + 2;
            sap.PreClose(hashtable);
            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);
            }



            //////////////////////////////////////////



            // Вычисляем подпись
            ContentInfo contentInfo = new ContentInfo(ss.ToArray());
            SignedCms   signedCms   = new SignedCms(contentInfo, true);
            CmsSigner   cmsSigner   = new CmsSigner(certificate);

            signedCms.ComputeSignature(cmsSigner, false);
            byte[] pk = signedCms.Encode();


            /*
             * // Помещаем подпись в документ
             * byte[] outc = new byte[intCSize];
             * PdfDictionary dic2 = new PdfDictionary();
             * Array.Copy(pk, 0, outc, 0, pk.Length);
             * dic2.Put(PdfName.CONTENTS, new PdfString(outc).SetHexWriting(true));
             * sap.Close(dic2);
             */


            Console.WriteLine(string.Format("Документ {0} успешно подписан на ключе {1} => {2}.",
                                            document, certificate.Subject, newSigned));

            /*
             * System.IO.StreamWriter sw = null;
             * System.IO.FileStream fs = new System.IO.FileStream("C:\\TEMP\\test_json_signed.json", System.IO.FileMode.Append, System.IO.FileAccess.Write);
             *
             *
             * sw = new System.IO.StreamWriter(fs, Encoding.GetEncoding(1251));
             * sw.WriteLine(Encoding.Default.GetString(pk));
             * sw.Close();
             *
             * fs.Dispose();
             * fs.Close();
             */


            // Помещаем подпись в документ
            byte[]        outc = new byte[intCSize];
            PdfDictionary dic2 = new PdfDictionary();

            Array.Copy(pk, 0, outc, 0, pk.Length);
            dic2.Put(PdfName.CONTENTS, new PdfString(outc).SetHexWriting(true));
            sap.Close(dic2);



            /////////////////////////////////////////////////////////////////////////////
        }
        protected override byte[] SignX509(byte[] pdf, bool detached)
        {
            _chain = GetChain();

            using (PdfReader reader = new PdfReader(pdf))
            {
                using (MemoryStream result = new MemoryStream())
                {
                    using (PdfStamper stp = PdfStamper.CreateSignature(reader, result, '\0', null, true))
                    {
                        PdfSignatureAppearance sap = stp.SignatureAppearance;

                        sap.Certificate = _chain;

                        var certificateInfo = new Juschubut.PdfDigitalSign.CertificateInfo(this.Certificate);

                        this.OnPrepareSignatureEvent(certificateInfo);

                        sap.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC;
                        PdfSignature dic = null;

                        if (detached)
                        {
                            dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
                        }
                        else
                        {
                            dic = new PdfSignature(PdfName.ADOBE_PPKMS, PdfName.ADBE_PKCS7_SHA1);
                        }

                        dic.Name = certificateInfo.CN;

                        this.AddSignature(reader, sap, certificateInfo);

                        sap.CryptoDictionary = dic;

                        int csize = detached ? 10000 : 4000;

                        var exc = new Dictionary <PdfName, int>();
                        exc.Add(PdfName.CONTENTS, csize * 2 + 2);
                        sap.PreClose(exc);

                        byte[] pk;

                        using (Stream stream = sap.GetRangeStream())
                        {
                            pk = this.SignMessage(stream, detached);
                        }

                        byte[] outc = new byte[csize];

                        PdfDictionary dic2 = new PdfDictionary();

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

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

                        outc = null;
                        pk   = null;

                        return(result.ToArray());
                    }
                }
            }
        }
        /**
         * Signs the document using the detached mode, CMS or CAdES equivalent.
         * @param sap the PdfSignatureAppearance
         * @param externalSignature the interface providing the actual signing
         * @param chain the certificate chain
         * @param crlList the CRL list
         * @param ocspClient the OCSP client
         * @param tsaClient the Timestamp client
         * @param provider the provider or null
         * @param estimatedSize the reserved size for the signature. It will be estimated if 0
         * @param cades true to sign CAdES equivalent PAdES-BES, false to sign CMS
         * @throws DocumentException 
         * @throws IOException 
         * @throws GeneralSecurityException 
         * @throws NoSuchAlgorithmException 
         * @throws Exception 
         */
        public static void SignDetached(PdfSignatureAppearance sap, IExternalSignature externalSignature, ICollection<X509Certificate> chain, ICollection<ICrlClient> crlList, IOcspClient ocspClient,
                ITSAClient tsaClient, int estimatedSize, CryptoStandard sigtype) {
            List<X509Certificate> certa = new List<X509Certificate>(chain);
            ICollection<byte[]> crlBytes = null;
            int i = 0;
            while (crlBytes == null && i < certa.Count)
        	    crlBytes = ProcessCrl(certa[i++], crlList);
            if (estimatedSize == 0) {
                estimatedSize = 8192;
                if (crlBytes != null) {
                    foreach (byte[] element in crlBytes) {
                        estimatedSize += element.Length + 10;
                    }
                }
                if (ocspClient != null)
                    estimatedSize += 4192;
                if (tsaClient != null)
                    estimatedSize += 4192;
            }
            sap.Certificate = certa[0];
            if(sigtype == CryptoStandard.CADES)
                sap.AddDeveloperExtension(PdfDeveloperExtension.ESIC_1_7_EXTENSIONLEVEL2);
            PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, sigtype == CryptoStandard.CADES ? PdfName.ETSI_CADES_DETACHED : PdfName.ADBE_PKCS7_DETACHED);
            dic.Reason = sap.Reason;
            dic.Location = sap.Location;
            dic.SignatureCreator = sap.SignatureCreator;
            dic.Contact = sap.Contact;
            dic.Date = new PdfDate(sap.SignDate); // time-stamp will over-rule this
            sap.CryptoDictionary = dic;

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

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

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

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

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

            PdfDictionary dic2 = new PdfDictionary();
            dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true));
            sap.Close(dic2);
        }
Esempio n. 29
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());
        }
Esempio n. 30
0
        private void SignUsingEstEIDCard2(string filename, string outfile)
        {
            statusHandler(Resources.VERIFYING_DOCUMENT, false);

            AcroFields af           = this.reader.AcroFields;
            ArrayList  names        = af.GetSignatureNames();
            bool       nextRevision = ((names != null) && (names.Count > 0));

            // already signed ?
            if (nextRevision)
            {
                // pick always first signature
                string   name   = (string)names[0];
                PdfPKCS7 pkc7   = af.VerifySignature(name);
                bool     verify = pkc7.Verify();
                if (!verify)
                {
                    string who = PdfPKCS7.GetSubjectFields(pkc7.SigningCertificate).GetField("CN");
                    throw new DocVerifyException(Resources.DOC_VERIFY_FAILED + who);
                }
            }

            statusHandler(Resources.CONNECTING_SMARTCARD, false);

            // open EstEID
            EstEIDReader estEidReader = new EstEIDReader();
            string       pkcs11_lib   = conf.PKCS11DriverPath;
            bool         b            = estEidReader.Open(pkcs11_lib);

            if (b == false)
            {
                throw new Exception(Resources.PKCS11_OPEN);
            }

            statusHandler(Resources.READ_CERTS, false);
            PKCS11Signer signer = LocateSigner(estEidReader);

            Org.BouncyCastle.X509.X509Certificate[] chain = X509Utils.LoadCertificate(signer.Cert.RawData);

            statusHandler(Resources.VERIFYING_OCSP, false);
            OCSPClientEstEID ocspClient = OCSPClient(chain[0]);

            if (ocspClient == null)
            {
                throw new Exception(this.lastError);
            }

            byte[] ocsp = ocspClient.GetEncoded();
            if (ocsp == null)
            {
                throw new RevocationException(ocspClient.lastError);
            }

            X509Certificate2 card = signer.Cert;
            Oid oid = card.SignatureAlgorithm;

            if (oid.Value != PkcsObjectIdentifiers.Sha1WithRsaEncryption.Id)
            {
                throw new Exception(Resources.INVALID_CERT);
            }

            PdfReader  reader   = new PdfReader(filename);
            Document   document = new Document(reader.GetPageSizeWithRotation(1));
            PdfStamper stp      = PdfStamper.CreateSignature(reader, new FileStream(outfile, FileMode.Create), '\0', null, nextRevision);

            if (metadata != null)
            {
                stp.XmpMetadata = metadata.getStreamedMetaData();
            }
            PdfSignatureAppearance sap = stp.SignatureAppearance;

            if (appearance.Visible)
            {
                if (appearance.SigLocation.UseSector)
                {
                    appearance.SigLocation.Bounds = document.PageSize;
                }
                sap.SetVisibleSignature(appearance.SigLocation, (int)appearance.Page, null);
            }
            sap.SignDate = DateTime.Now;
            sap.SetCrypto(null, chain, null, null);
            sap.Reason      = (appearance.Reason.Length > 0) ? appearance.Reason : null;
            sap.Location    = (appearance.Location.Length > 0) ? appearance.Location : null;
            sap.Contact     = (appearance.Contact.Length > 0) ? appearance.Contact : null;
            sap.Acro6Layers = true;
            sap.Render      = appearance.SignatureRender;
            sap.Layer2Text  = appearance.SignatureText(sap.SignDate, chain[0]);
            PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_SHA1);

            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;
            sap.SetExternalDigest(new byte[SIGNATURE_LENGTH], new byte[Digest.SHA1_LENGTH], "RSA");

            // expect 6K to be enough if TSA response, else 2K ?
            int       csize = (stamp != null) ? 1024 * 6 : 1024 * 2;
            Hashtable exc   = new Hashtable();

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

            // compute hash based on PDF bytes
            byte[] digest = ComputeHash(estEidReader, sap);

            statusHandler(Resources.ADD_SIGNATURE, false);
            // sign hash
            byte[] rsadata = EstEIDCardSign(estEidReader, signer, digest);
            // if null, user requested Cancel
            if (rsadata == null)
            {
                throw new Exception(Resources.CARD_INTERNAL_ERROR);
            }

            // create PKCS#7 envelope
            PdfPKCS7 pk7 = new PdfPKCS7(null, chain, null, "SHA1", true);

            pk7.SetExternalDigest(rsadata, digest, "RSA");

            byte[] pk = pk7.GetEncodedPKCS7();

            // user wants to add TSA response ?
            if (stamp != null && pk != null)
            {
                statusHandler(Resources.TSA_REQUEST, false);
                pk = TimestampAuthorityResponse(estEidReader, pk);
            }

            // PKCS#7 bytes too large ?
            if (pk.Length >= csize)
            {
                throw new Exception(Resources.MEMORY_ERROR);
            }

            byte[] outc = new byte[csize];

            PdfDictionary dic2 = new PdfDictionary();

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

            dic2.Put(PdfName.CONTENTS, new PdfString(outc).SetHexWriting(true));
            sap.Close(dic2);
        }
Esempio n. 31
0
        /// <summary>
        /// Firma un documento
        /// </summary>
        /// <param name="Source">Documento origen</param>
        /// <param name="Target">Documento destino</param>
        /// <param name="Certificate">Certificado a utilizar</param>
        /// <param name="Reason">Razón de la firma</param>
        /// <param name="Location">Ubicación</param>
        /// <param name="AddVisibleSign">Establece si hay que agregar la firma visible al documento</param>
        public static void SignHashed(string Source, string Target, SysX509.X509Certificate2 Certificate, string Reason, string Location, bool AddVisibleSign)
        {
            X509CertificateParser objCP = new X509CertificateParser();

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

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

            if (AddVisibleSign)
            {
                objSA.SetVisibleSignature(new Rectangle(50, 50, 150, 100), 2, null);
            }

            objSA.SignDate = DateTime.Now;
            objSA.SetCrypto(null, objChain, null, null);
            objSA.Reason      = Reason;
            objSA.Location    = Location;
            objSA.Acro6Layers = true;
            objSA.Render      = PdfSignatureAppearance.SignatureRender.NameAndDescription;
            PdfSignature objSignature = new PdfSignature(PdfName.ADOBE_PPKMS, PdfName.ADBE_PKCS7_SHA1);

            objSignature.Date = new PdfDate(objSA.SignDate);
            objSignature.Name = PdfPKCS7.GetSubjectFields(objChain[0]).GetField("CN");
            if (objSA.Reason != null)
            {
                objSignature.Reason = objSA.Reason;
            }
            if (objSA.Location != null)
            {
                objSignature.Location = objSA.Location;
            }
            objSA.CryptoDictionary = objSignature;
            int       intCSize = 4000;
            Hashtable objTable = new Hashtable();

            objTable[PdfName.CONTENTS] = intCSize * 2 + 2;
            objSA.PreClose(objTable);

            HashAlgorithm objSHA1 = new SHA1CryptoServiceProvider();

            Stream objStream = objSA.RangeStream;
            int    intRead   = 0;

            byte[] bytBuffer = new byte[8192];
            while ((intRead = objStream.Read(bytBuffer, 0, 8192)) > 0)
            {
                objSHA1.TransformBlock(bytBuffer, 0, intRead, bytBuffer, 0);
            }
            objSHA1.TransformFinalBlock(bytBuffer, 0, 0);

            byte[] bytPK  = SignMsg(objSHA1.Hash, Certificate, false);
            byte[] bytOut = new byte[intCSize];

            PdfDictionary objDict = new PdfDictionary();

            Array.Copy(bytPK, 0, bytOut, 0, bytPK.Length);

            objDict.Put(PdfName.CONTENTS, new PdfString(bytOut).SetHexWriting(true));
            objSA.Close(objDict);
        }
Esempio n. 32
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();
        }
Esempio n. 33
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());
                }
            }
        }