예제 #1
0
파일: TedaSign.cs 프로젝트: page2me/TeDA
        public void setKeyStore(Pkcs12Store keystore, string hashAlgorithm) //Getkey
        {
            //get name
            String alias = "";

            foreach (string al in keystore.Aliases)
            {
                if (keystore.IsKeyEntry(al) && keystore.GetKey(al).Key.IsPrivate) // ****  what this if do ?
                {
                    alias = al;
                    break;
                }
            }

            //get privatekey
            this.privateKey = keystore.GetKey(alias).Key;

            //create instance of Cretificate list for Long Time
            this.chain = new List <Org.BouncyCastle.X509.X509Certificate>();
            foreach (X509CertificateEntry entry in keystore.GetCertificateChain(alias))
            {
                this.chain.Add(entry.Certificate);
            }

            this.signature = new PrivateKeySignature(privateKey, hashAlgorithm);
        }
예제 #2
0
파일: TedaSign.cs 프로젝트: page2me/TeDA
        public void setKeyStore(X509Certificate2 cert, string hashAlgorithm) //Getkey
        {
            /*GET Certificate chain from Cert and translate info x509 Bouncycastle List*/
            Org.BouncyCastle.X509.X509Certificate bcCert = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(cert); // ไม่ได้เก็ต ของผู้ออก Certificate Chain มาด้วย
            chain = new List <Org.BouncyCastle.X509.X509Certificate> {
                bcCert
            };

            // Initial .netx509 certchain and build chain
            X509Chain cert_chain = new X509Chain();

            cert_chain.Build(cert);

            int i = 0;

            //Add chain into bouncyCastle.chain
            foreach (X509ChainElement entry in cert_chain.ChainElements)
            {
                if (i != 0)//Skip first certchain due to cert_chain.Build provided first chain(entry.chain.[0])
                {
                    this.chain.Add(Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(entry.Certificate));
                }
                i++;
            }

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

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

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

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

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

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

            PdfDictionary dic2 = new PdfDictionary();
            dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true));
            sap.Close(dic2);
        }
        public static void Sign(IExternalSignature externalSignature, X509Certificate2 rawCertificate, string sourcePdfPath, string destinationPdfPath)
        {
            if (externalSignature == null)
            {
                throw new ArgumentNullException(nameof(externalSignature));
            }
            if (rawCertificate == null)
            {
                throw new ArgumentNullException(nameof(rawCertificate));
            }
            if (sourcePdfPath == null)
            {
                throw new ArgumentNullException(nameof(sourcePdfPath));
            }
            if (destinationPdfPath == null)
            {
                throw new ArgumentNullException(nameof(destinationPdfPath));
            }

            using PdfReader reader = new PdfReader(sourcePdfPath);
            Org.BouncyCastle.X509.X509Certificate   bCert = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(rawCertificate);
            Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { bCert };

            using FileStream stream = new FileStream(destinationPdfPath, FileMode.OpenOrCreate);
            PdfSigner signer = new PdfSigner(reader, stream, new StampingProperties());

            signer.SetSignatureEvent(new SignatureEvent());
            signer.SignDetached(externalSignature, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES);
        }
예제 #5
0
        //Sample from: http://www.rahulsingla.com/blog/2012/09/digitally-sign-and-verify-pdf-documents-in-c-using-itextsharp-5-3-x-library
        // http://stackoverflow.com/questions/14997118/how-do-i-sign-a-pdf-document-using-a-certificate-from-the-windows-cert-store

        /// <summary>
        /// Signs a PDF document using iTextSharp library
        /// </summary>
        /// <param name="certSubjectName">Cerificate subject (prefix) in local certStore.</param>
        /// <param name="sourceDocument">The path of the source pdf document which is to be signed</param>
        /// <param name="destinationPath">The path at which the signed pdf document should be generated</param>
        /// <param name="reason">String describing the reason for signing, would be embedded as part of the signature</param>
        /// <param name="location">Location where the document was signed, would be embedded as part of the signature</param>
        /// <param name="allowInvalidCertificate">Allows also usage of invalid certificate from store.</param>
        public static byte[] SignPdf(string certSubjectName, byte[] sourceDocument, string reason, string location, bool allowInvalidCertificate)
        {
            try
            {
                // reader and stamper
                using (PdfReader reader = new PdfReader(sourceDocument))
                {
                    using (MemoryStream fout = new MemoryStream())
                    {
                        PdfStamper stamper = PdfStamper.CreateSignature(reader, fout, '\0');
                        // appearance
                        PdfSignatureAppearance appearance = stamper.SignatureAppearance;
                        appearance.Reason   = reason;
                        appearance.Location = location;
                        // digital signature

                        ICollection <Org.BouncyCastle.X509.X509Certificate> certChain;
                        IExternalSignature es = ResolveExternalSignatureFromCertStore(certSubjectName, allowInvalidCertificate, out certChain);

                        MakeSignature.SignDetached(appearance, es, certChain, null, null, null, 0, CryptoStandard.CMS);

                        stamper.Close();
                        return(fout.ToArray());
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.TraceError("Exception during pdf sign: {0}", ex.Message);
                throw;
            }
        }
예제 #6
0
        /**
         * Signs the xml using the enveloped mode, with optional xpath transform (see XmlSignatureAppearance).
         * @param sap the XmlSignatureAppearance
         * @param externalSignature  the interface providing the actual signing
         * @param keyInfo KeyInfo for verification
         * @throws GeneralSecurityException
         * @throws IOException
         * @throws DocumentException
         */
        public static void SignXmlDSig(XmlSignatureAppearance sap, IExternalSignature externalSignature, KeyInfoClause keyInfo) {

            VerifyArguments(sap, externalSignature);
            List<XmlElement> references = new List<XmlElement>(1);
            references.Add(GenerateContentReference(sap.GetXmlLocator().GetDocument(), sap, null));
                
            XmlElement signature = GenerateSignatureElement(sap.GetXmlLocator(), null, false);
            Sign(signature, sap.GetXmlLocator(), externalSignature, references, null, keyInfo);
            sap.Close();    
        }
예제 #7
0
        /**
         * Signs the xml using the enveloped mode, with optional xpath transform (see XmlSignatureAppearance).
         * @param sap the XmlSignatureAppearance
         * @param externalSignature  the interface providing the actual signing
         * @param keyInfo KeyInfo for verification
         * @throws GeneralSecurityException
         * @throws IOException
         * @throws DocumentException
         */
        public static void SignXmlDSig(XmlSignatureAppearance sap, IExternalSignature externalSignature, KeyInfoClause keyInfo)
        {
            VerifyArguments(sap, externalSignature);
            List <XmlElement> references = new List <XmlElement>(1);

            references.Add(GenerateContentReference(sap.GetXmlLocator().GetDocument(), sap, null));

            XmlElement signature = GenerateSignatureElement(sap.GetXmlLocator(), null, false);

            Sign(signature, sap.GetXmlLocator(), externalSignature, references, null, keyInfo);
            sap.Close();
        }
예제 #8
0
        private static void SignPdf(X509Certificate2 certificate, IExternalSignature externalSignature, string signedPdfName)
        {
            var bCert = DotNetUtilities.FromX509Certificate(certificate);
            var chain = new Org.BouncyCastle.X509.X509Certificate[] { bCert };

            using (var reader = new PdfReader("Hello World.pdf"))
            {
                using (var stream = new FileStream(signedPdfName, FileMode.OpenOrCreate))
                {
                    var signer = new PdfSigner(reader, stream, false);
                    signer.SignDetached(externalSignature, chain, null, null, null, 0, PdfSigner.CryptoStandard.CMS);
                }
            }
        }
예제 #9
0
        private static void VerifyArguments(XmlSignatureAppearance sap, IExternalSignature externalSignature)
        {
            if (sap.GetXmlLocator() == null)
            {
                throw new DocumentException(MessageLocalization.GetComposedMessage("xmllocator.cannot.be.null"));
            }
            if (!externalSignature.GetHashAlgorithm().Equals(SecurityConstants.SHA1))
            {
                throw new UnsupportedPdfException(MessageLocalization.GetComposedMessage("support.only.sha1.hash.algorithm"));
            }

            if (!externalSignature.GetEncryptionAlgorithm().Equals(SecurityConstants.RSA) &&
                !externalSignature.GetEncryptionAlgorithm().Equals(SecurityConstants.DSA))
            {
                throw new UnsupportedPdfException(MessageLocalization.GetComposedMessage("support.only.rsa.and.dsa.algorithms"));
            }
        }
예제 #10
0
        /**
         * Signs the xml with XAdES BES using the enveloped mode, with optional xpath transform (see XmlSignatureAppearance).
         * @param sap the XmlSignatureAppearance
         * @param externalSignature  the interface providing the actual signing
         * @param chain the certificate chain
         * @param includeSignaturePolicy if true SignaturePolicyIdentifier will be included (XAdES-EPES)
         * @throws GeneralSecurityException
         * @throws IOException
         * @throws DocumentException
         */
        public static void SignXades(XmlSignatureAppearance sap, IExternalSignature externalSignature, X509Certificate[] chain,
                                     bool includeSignaturePolicy)
        {
            VerifyArguments(sap, externalSignature);
            String contentReferenceId = SecurityConstants.Reference_ + GetRandomId();
            String signedPropertiesId = SecurityConstants.SignedProperties_ + GetRandomId();
            String signatureId        = SecurityConstants.Signature_ + GetRandomId();

            XmlDocument doc = sap.GetXmlLocator().GetDocument();

            doc.XmlResolver = null;
            KeyInfoClause     keyInfo    = GenerateKeyInfo(chain, sap);
            List <XmlElement> references = new List <XmlElement>(2);

            XmlElement signature = GenerateSignatureElement(sap.GetXmlLocator(), signatureId, true);

            String[] signaturePolicy = null;
            if (includeSignaturePolicy)
            {
                signaturePolicy = new String[2];
                if (externalSignature.GetEncryptionAlgorithm().Equals(SecurityConstants.RSA))
                {
                    signaturePolicy[0] = SecurityConstants.OID_RSA_SHA1;
                    signaturePolicy[1] = SecurityConstants.OID_RSA_SHA1_DESC;
                }
                else
                {
                    signaturePolicy[0] = SecurityConstants.OID_DSA_SHA1;
                    signaturePolicy[1] = SecurityConstants.OID_DSA_SHA1_DESC;
                }
            }

            XmlElement signedProperty;
            XmlElement dsObject = GenerateXadesObject(sap, signatureId, contentReferenceId, signedPropertiesId, signaturePolicy, out signedProperty);

            references.Add(GenerateCustomReference(doc, signedProperty, "#" + signedPropertiesId, SecurityConstants.SignedProperties_Type, null));
            references.Add(GenerateContentReference(doc, sap, contentReferenceId));

            Sign(signature, sap.GetXmlLocator(), externalSignature, references, dsObject, keyInfo);

            sap.Close();
        }
 private void SelectSignature(
     PdfRequestDTO request,
     out X509Certificate2 CERTIFICATE,
     out IExternalSignature externalSignature)
 {
     try
     {
         SmartCardManager smartCardManager = SmartCardManager.getInstance();
         var smartCardCertificate          = smartCardManager.getSignatureCertificate(false, false);
         var signer = smartCardManager.getSigner(request.DonglePassword, smartCardCertificate);
         CERTIFICATE       = smartCardCertificate.asX509Certificate2();
         externalSignature = new SmartCardSignature(signer, CERTIFICATE, "SHA-256");
     }
     catch (Exception ex)
     {
         CERTIFICATE       = null;
         externalSignature = null;
         MessageBox.Show(ex.Message);
     }
 }
예제 #12
0
        protected void SignDocumentSignature(string filePath, ElectronicSignatureInfoDTO signatureInfo)
        {
            PdfSigner pdfSigner = new PdfSigner(new PdfReader(SRC), new FileStream(filePath, FileMode.Create),
                                                new StampingProperties());

            pdfSigner.SetCertificationLevel(PdfSigner.CERTIFIED_NO_CHANGES_ALLOWED);

            // Set the name indicating the field to be signed.
            // The field can already be present in the document but shall not be signed
            pdfSigner.SetFieldName("signature");

            ImageData clientSignatureImage = ImageDataFactory.Create(IMAGE_PATH);

            // If you create new signature field (or use SetFieldName(System.String) with
            // the name that doesn't exist in the document or don't specify it at all) then
            // the signature is invisible by default.
            PdfSignatureAppearance signatureAppearance = pdfSigner.GetSignatureAppearance();

            signatureAppearance.SetRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC);
            signatureAppearance.SetReason("");
            signatureAppearance.SetLocationCaption("");
            signatureAppearance.SetSignatureGraphic(clientSignatureImage);
            signatureAppearance.SetPageNumber(signatureInfo.PageNumber);
            signatureAppearance.SetPageRect(new Rectangle(signatureInfo.Left, signatureInfo.Bottom,
                                                          25, 25));

            char[]             password = "******".ToCharArray();
            IExternalSignature pks      = GetPrivateKeySignature(CERT_PATH, password);

            X509Certificate[]      chain        = GetCertificateChain(CERT_PATH, password);
            OCSPVerifier           ocspVerifier = new OCSPVerifier(null, null);
            OcspClientBouncyCastle ocspClient   = new OcspClientBouncyCastle(ocspVerifier);
            List <ICrlClient>      crlClients   = new List <ICrlClient>(new[] { new CrlClientOnline() });

            // Sign the document using the detached mode, CMS or CAdES equivalent.
            // This method closes the underlying pdf document, so the instance
            // of PdfSigner cannot be used after this method call
            pdfSigner.SignDetached(pks, chain, crlClients, ocspClient, null, 0,
                                   PdfSigner.CryptoStandard.CMS);
        }
예제 #13
0
        /// <summary>
        ///     The method Sign Pdf.
        /// </summary>
        /// <param name="input">
        /// The pdf to signed.
        /// </param>
        /// <param name="_pkcs12Store">
        /// Pkcs12Store private key.
        /// </param>
        /// <param name="password">
        /// password of Pkcs12Store key.
        /// </param>
        /// <param name="reason">
        /// reason for digital signature.
        /// </param>
        ///<param name="location">
        /// signing location.
        /// </param>
        /// ///<param name="signDate">
        /// signing time.
        /// </param>
        /// <returns>
        ///     The <see cref="byte[]" />.
        /// </returns>
        public byte[] sign(byte[] input, Pkcs12Store _pkcs12Store, string password, string reason, string location, DateTime signDate)
        {
            //_pkcs12Store = pkcs12Store;
            Pkcs12Store pkcs12Store = _pkcs12Store;
            //Pkcs12Store pkcs12Store = new Pkcs12Store((Stream)new FileStream(certificatePath, FileMode.Open, FileAccess.Read), password.ToCharArray());
            string str6 = (string)null;

            foreach (string aliase in pkcs12Store.Aliases)
            {
                if (pkcs12Store.IsKeyEntry(aliase))
                {
                    str6 = aliase;
                }
            }

            AsymmetricKeyParameter key = pkcs12Store.GetKey(str6).Key;
            PdfReader pdfReader        = new PdfReader(input);

            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (PdfStamper signature = PdfStamper.CreateSignature(pdfReader, (Stream)memoryStream, char.MinValue))
                {
                    PdfSignatureAppearance signatureAppearance = signature.SignatureAppearance;
                    signatureAppearance.Reason             = reason;
                    signatureAppearance.Location           = location;
                    signatureAppearance.SignDate           = signDate;
                    signatureAppearance.CertificationLevel = 1;
                    IExternalSignature iexternalSignature = (IExternalSignature) new PrivateKeySignature((ICipherParameters)key, "SHA-256");
                    MakeSignature.SignDetached(signatureAppearance, iexternalSignature, (ICollection <X509Certificate>) new X509Certificate[1]
                    {
                        //pkcs12Store.GetCertificate(str6).get_Certificate()
                        pkcs12Store.GetCertificate(str6).Certificate
                    }, (ICollection <ICrlClient>)null, (IOcspClient)null, (ITSAClient)null, 0, (CryptoStandard)0);
                    signature.Close();
                }
                this._result = memoryStream.ToArray();
            }
            return(this._result);
        }
예제 #14
0
        /**
         * Signs the xml with XAdES BES using the enveloped mode, with optional xpath transform (see XmlSignatureAppearance).
         * @param sap the XmlSignatureAppearance
         * @param externalSignature  the interface providing the actual signing
         * @param chain the certificate chain
         * @throws GeneralSecurityException
         * @throws IOException
         * @throws DocumentException
         */
        public static void SignXadesBes(XmlSignatureAppearance sap, IExternalSignature externalSignature, X509Certificate[] chain)
        {
            VerifyArguments(sap, externalSignature);
            String contentReferenceId = SecurityConstants.Reference_ + GetRandomId();
            String signedPropertiesId = SecurityConstants.SignedProperties_ + GetRandomId();
            String signatureId        = SecurityConstants.Signature_ + GetRandomId();

            XmlDocument       doc        = sap.GetXmlLocator().GetDocument();
            KeyInfoClause     keyInfo    = GenerateKeyInfo(chain, sap);
            List <XmlElement> references = new List <XmlElement>(2);

            XmlElement signature = GenerateSignatureElement(sap.GetXmlLocator(), signatureId, true);
            XmlElement signedProperty;
            XmlElement dsObject = GenerateXadesBesObject(sap, signatureId, contentReferenceId, signedPropertiesId, out signedProperty);

            references.Add(GenerateCustomReference(doc, signedProperty, "#" + signedPropertiesId, SecurityConstants.SignedProperties_Type, null));
            references.Add(GenerateContentReference(doc, sap, contentReferenceId));

            Sign(signature, sap.GetXmlLocator(), externalSignature, references, dsObject, keyInfo);

            sap.Close();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <param name="chain"></param>
        /// <param name="pks"></param>
        /// <param name="subfilter"></param>
        /// <param name="reason"></param>
        /// <param name="location"></param>
        /// <param name="crlList"></param>
        /// <param name="ocspClient"></param>
        /// <param name="tsaClient"></param>
        /// <param name="estimatedSize"></param>
        /// <returns></returns>
        private static byte[] SignDocument(String input,
                         ICollection<Org.BouncyCastle.X509.X509Certificate> chain,
                         IExternalSignature pks,
                         CryptoStandard subfilter,
                         String reason, String location,
                         ICollection<ICrlClient> crlList,
                         IOcspClient ocspClient,
                         ITSAClient tsaClient,
                         int estimatedSize)
        {
            using (var stream = new MemoryStream())
            {
                // Creating the reader and the stamper
                PdfReader reader = null;
                PdfStamper stamper = null;
                try
                {
                    reader = new PdfReader(input);
                    stamper = PdfStamper.CreateSignature(reader, stream, '\0');

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

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

                return stream.GetBuffer();
            }
        }
예제 #16
0
 /**
  * Signs the xml with XAdES BES using the enveloped mode, with optional xpath transform (see XmlSignatureAppearance).
  * @param sap the XmlSignatureAppearance
  * @param externalSignature  the interface providing the actual signing
  * @param chain the certificate chain
  * @throws GeneralSecurityException
  * @throws IOException
  * @throws DocumentException
  */
 public static void SignXadesEpes(XmlSignatureAppearance sap, IExternalSignature externalSignature, X509Certificate[] chain)
 {
     SignXades(sap, externalSignature, chain, true);
 }
예제 #17
0
        /**
         * Signs the xml with XAdES BES using the enveloped mode, with optional xpath transform (see XmlSignatureAppearance).
         * @param sap the XmlSignatureAppearance
         * @param externalSignature  the interface providing the actual signing
         * @param chain the certificate chain
         * @throws GeneralSecurityException
         * @throws IOException
         * @throws DocumentException
         */
        public static void SignXadesBes(XmlSignatureAppearance sap, IExternalSignature externalSignature, X509Certificate[] chain) {

            VerifyArguments(sap, externalSignature);
            String contentReferenceId = SecurityConstants.Reference_ + GetRandomId();
            String signedPropertiesId = SecurityConstants.SignedProperties_ + GetRandomId();
            String signatureId = SecurityConstants.Signature_ + GetRandomId();

            XmlDocument doc = sap.GetXmlLocator().GetDocument();
            KeyInfoClause keyInfo = GenerateKeyInfo(chain, sap);
            List<XmlElement> references = new List<XmlElement>(2);
            
            XmlElement signature = GenerateSignatureElement(sap.GetXmlLocator(), signatureId, true);
            XmlElement signedProperty;
            XmlElement dsObject = GenerateXadesBesObject(sap, signatureId, contentReferenceId, signedPropertiesId, out signedProperty);
            
            references.Add(GenerateCustomReference(doc, signedProperty, "#" + signedPropertiesId, SecurityConstants.SignedProperties_Type, null));
            references.Add(GenerateContentReference(doc, sap, contentReferenceId));

            Sign(signature, sap.GetXmlLocator(), externalSignature, references, dsObject, keyInfo);

            sap.Close();
        }
예제 #18
0
        /// <summary>
        /// Assina um pdf com um certificado válido
        /// </summary>
        /// <param name="certificate">X509 Certificado</param>
        /// <param name="dadosAssinatura">Dados da assinatura (DadosAssinatura)</param>
        /// <returns></returns>
        public static byte[] AssinarPdf(X509Certificate2 certificate, DadosAssinatura dadosAssinatura)
        {
            try
            {
                // ler arquivo e insere dados de assinatura
                using (PdfReader reader = new PdfReader(dadosAssinatura.Arquivo))
                {
                    using (MemoryStream fout = new MemoryStream())
                    {
                        PdfStamper stamper = PdfStamper.CreateSignature(reader, fout, '\0', null, true);

                        // texto marca d'água
                        Font f = new Font(Font.FontFamily.TIMES_ROMAN, 8);

                        string[] dados = certificate.GetNameInfo(X509NameType.SimpleName, false).Split(':');

                        Phrase pAssinado = new Phrase($@"Este documento foi assinado digitalmente por: {dados[0]}", f);

                        // Imagem marca d'água
                        //Image img = dadosAssinatura.Imagem;
                        float w = 200F;
                        float h = 75.2F;
                        // Transparência
                        PdfGState gs1 = new PdfGState();

                        // Propriedades
                        PdfContentByte over;
                        Rectangle      pagesize;

                        int n = reader.NumberOfPages;

                        //Página
                        var  pagina       = 1;
                        bool todasPaginas = false;
                        pagesize = reader.GetPageSizeWithRotation(pagina);

                        switch (dadosAssinatura.PaginaAssinatura)
                        {
                        case EnumPaginaAssinatura.PRIMEIRA:
                            pagina = 1;
                            break;

                        case EnumPaginaAssinatura.ULTIMA:
                            pagina = reader.NumberOfPages;
                            break;

                        case EnumPaginaAssinatura.TODAS:
                            todasPaginas = true;
                            break;

                        default:
                            pagina = 1;
                            break;
                        }

                        float x, y, xr = 0, hr = 0, yr = 0, wr = 0;
                        //Posição da assinatura
                        switch (dadosAssinatura.Posicao)
                        {
                        case EnumPosicao.ACIMA_ESQUERDA:
                            x  = (float)(pagesize.Left * 0.88);
                            y  = (float)(pagesize.Top * 0.88);
                            xr = x * 0.5F;
                            wr = w;
                            yr = pagesize.Top * 0.97F;
                            hr = pagesize.Top * 0.88F;

                            break;

                        case EnumPosicao.ACIMA_DIREITA:
                            x  = (float)(pagesize.Right * 0.64);
                            y  = (float)(pagesize.Top * 0.88);
                            xr = pagesize.Right * 0.97F;
                            wr = xr - w;
                            yr = pagesize.Top * 0.97F;
                            hr = pagesize.Top * 0.88F;
                            break;

                        case EnumPosicao.ABAIXO_ESQUERDA:
                            x  = (float)(pagesize.Left * 0.88);
                            y  = (float)(pagesize.Bottom * 0.88);
                            xr = x * 0.5F;
                            wr = w;
                            yr = y;
                            hr = h;
                            break;

                        case EnumPosicao.ABAIXO_DIREITA:
                            x  = (float)(pagesize.Right * 0.64);
                            y  = (float)(pagesize.Bottom * 0.88);
                            xr = x * 1.53F;
                            wr = w * 1.9F;
                            yr = y;
                            hr = h;
                            break;

                        case EnumPosicao.ABAIXO_CENTRO:
                            x  = (pagesize.Right * 1.74f - pagesize.Left) / 1.32f;
                            y  = (float)(pagesize.Bottom * 0.76);
                            xr = x * 1.53F;
                            wr = w * 1.53F;
                            yr = y;
                            hr = h;
                            break;

                        default:
                            x  = (float)(pagesize.Left * 0.88);
                            y  = (float)(pagesize.Top * 0.88);
                            xr = x * 1.53F;
                            wr = w * 1.9F;
                            break;
                        }

                        PdfSignatureAppearance appearance = stamper.SignatureAppearance;
                        appearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION;
                        appearance.Layer2Text             = "";
                        appearance.Layer4Text             = "";
                        Rectangle rect = new Rectangle(wr, hr, xr, yr);

                        //Plota a assinatura no pdf
                        if (todasPaginas)
                        {
                            for (int i = 1; i <= n; i++)
                            {
                                over = stamper.GetOverContent(i);
                                over.SaveState();
                                over.SetGState(gs1);
                                //over.AddImage(img, w, 0, 0, h, x, y);
                                ColumnText.ShowTextAligned(over, Element.ALIGN_TOP, pAssinado, x + 57, y + 15, 0);
                                ColumnText.ShowTextAligned(over, Element.ALIGN_TOP, pCodigAut, x + 84.5f, y + 5, 0);
                                over.RestoreState();
                            }
                        }
                        else
                        {
                            over = stamper.GetOverContent(pagina);

                            over.SaveState();
                            over.SetGState(gs1);
                            //over.AddImage(img, w, 0, 0, h, x, y);
                            ColumnText.ShowTextAligned(over, Element.ALIGN_TOP, pAssinado, x + 57, y + 15, 0);
                            ColumnText.ShowTextAligned(over, Element.ALIGN_TOP, pCodigAut, x + 84.5f, y + 5, 0);
                            over.RestoreState();
                        }



                        ICollection <Org.BouncyCastle.X509.X509Certificate> certChain;
                        IExternalSignature es = ResolveExternalSignatureFromCertStore(certificate, dadosAssinatura.CertificadoValido, out certChain);

                        //Autenticação da assinatura digital
                        MakeSignature.SignDetached(appearance, es, certChain, null, null, null, 0, CryptoStandard.CADES);

                        stamper.Close();
                        return(fout.ToArray());
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"Erro durante assinatura digital do pdf: {ex.Message}");
            }
        }
예제 #19
0
 /**
  * Signs the xml using the enveloped mode, with optional xpath transform (see XmlSignatureAppearance).
  * @param sap the XmlSignatureAppearance
  * @param externalSignature  the interface providing the actual signing
  * @param publicKey PublicKey for verification
  * @throws GeneralSecurityException
  * @throws IOException
  * @throws DocumentException
  */
 public static void signXmlDSig(XmlSignatureAppearance sap,
     IExternalSignature externalSignature, PublicKey publicKey) {
         throw new NotImplementedException("Xml signatures are not supported yet");
 } 
        /**
         * Signs the xml using the enveloped mode, with optional xpath transform (see XmlSignatureAppearance).
         * @param sap the XmlSignatureAppearance
         * @param externalSignature  the interface providing the actual signing
         * @param keyInfo KeyInfo for verification
         * @throws GeneralSecurityException
         * @throws IOException
         * @throws DocumentException
         */
        //public static void SignXmlDSig(XmlSignatureAppearance sap, IExternalSignature externalSignature, KeyInfoClause keyInfo) {

        //    VerifyArguments(sap, externalSignature);
        //    List<XmlElement> references = new List<XmlElement>(1);
        //    references.Add(GenerateContentReference(sap.GetXmlLocator().GetDocument(), sap, null));
                
        //    XmlElement signature = GenerateSignatureElement(sap.GetXmlLocator(), null, false);
        //    Sign(signature, sap.GetXmlLocator(), externalSignature, references, null, keyInfo);
        //    sap.Close();    
        //}

        /**
         * Signs the xml with XAdES BES using the enveloped mode, with optional xpath transform (see XmlSignatureAppearance).
         * @param sap the XmlSignatureAppearance
         * @param externalSignature  the interface providing the actual signing
         * @param chain the certificate chain
         * @param includeSignaturePolicy if true SignaturePolicyIdentifier will be included (XAdES-EPES)
         * @throws GeneralSecurityException
         * @throws IOException
         * @throws DocumentException
         */
        //public static void SignXades(XmlSignatureAppearance sap, IExternalSignature externalSignature, X509Certificate[] chain,
        //    bool includeSignaturePolicy) {

        //    VerifyArguments(sap, externalSignature);
        //    String contentReferenceId = SecurityConstants.Reference_ + GetRandomId();
        //    String signedPropertiesId = SecurityConstants.SignedProperties_ + GetRandomId();
        //    String signatureId = SecurityConstants.Signature_ + GetRandomId();

        //    XmlDocument doc = sap.GetXmlLocator().GetDocument();
        //    KeyInfoClause keyInfo = GenerateKeyInfo(chain, sap);
        //    List<XmlElement> references = new List<XmlElement>(2);
            
        //    XmlElement signature = GenerateSignatureElement(sap.GetXmlLocator(), signatureId, true);
        //    String[] signaturePolicy = null;
        //    if(includeSignaturePolicy) {
        //        signaturePolicy = new String[2];
        //        if(externalSignature.GetEncryptionAlgorithm().Equals(SecurityConstants.RSA)) {
        //            signaturePolicy[0] = SecurityConstants.OID_RSA_SHA1;
        //            signaturePolicy[1] = SecurityConstants.OID_RSA_SHA1_DESC;
        //        }
        //        else {
        //            signaturePolicy[0] = SecurityConstants.OID_DSA_SHA1;
        //            signaturePolicy[1] = SecurityConstants.OID_DSA_SHA1_DESC;
        //        }
        //    }

        //    XmlElement signedProperty;
        //    XmlElement dsObject = GenerateXadesObject(sap, signatureId, contentReferenceId, signedPropertiesId, signaturePolicy, out signedProperty);
            
        //    references.Add(GenerateCustomReference(doc, signedProperty, "#" + signedPropertiesId, SecurityConstants.SignedProperties_Type, null));
        //    references.Add(GenerateContentReference(doc, sap, contentReferenceId));

        //    Sign(signature, sap.GetXmlLocator(), externalSignature, references, dsObject, keyInfo);

        //    sap.Close();
        //}

        /**
         * Signs the xml with XAdES BES using the enveloped mode, with optional xpath transform (see XmlSignatureAppearance).
         * @param sap the XmlSignatureAppearance
         * @param externalSignature  the interface providing the actual signing
         * @param chain the certificate chain
         * @throws GeneralSecurityException
         * @throws IOException
         * @throws DocumentException
         */
        //public static void SignXadesBes(XmlSignatureAppearance sap, IExternalSignature externalSignature, X509Certificate[] chain) {
        //    SignXades(sap, externalSignature, chain, false);
        //}

        /**
         * Signs the xml with XAdES BES using the enveloped mode, with optional xpath transform (see XmlSignatureAppearance).
         * @param sap the XmlSignatureAppearance
         * @param externalSignature  the interface providing the actual signing
         * @param chain the certificate chain
         * @throws GeneralSecurityException
         * @throws IOException
         * @throws DocumentException
         */
        //public static void SignXadesEpes(XmlSignatureAppearance sap, IExternalSignature externalSignature, X509Certificate[] chain) {
        //    SignXades(sap, externalSignature, chain, true);
        //}

        /**
         * Signs the xml using the enveloped mode, with optional xpath transform (see XmlSignatureAppearance).
         * @param sap the XmlSignatureAppearance
         * @param externalSignature  the interface providing the actual signing
         * @param chain the certificate chain
         * @throws GeneralSecurityException
         * @throws IOException
         * @throws DocumentException
         */
        //public static void SignXmlDSig(XmlSignatureAppearance sap,
        //    IExternalSignature externalSignature, X509Certificate[] chain) {
        //    SignXmlDSig(sap, externalSignature, new KeyInfoX509Data(chain[0].GetEncoded()));
        //}

        /**
         * Signs the xml using the enveloped mode, with optional xpath transform (see XmlSignatureAppearance).
         * @param sap the XmlSignatureAppearance
         * @param externalSignature  the interface providing the actual signing
         * @param publicKey PublicKey for verification
         * @throws GeneralSecurityException
         * @throws IOException
         * @throws DocumentException
         */
        //public static void SignXmlDSig(XmlSignatureAppearance sap,
        //    IExternalSignature externalSignature, AsymmetricAlgorithm publicKey) {
        //    SignXmlDSig(sap, externalSignature, GenerateKeyInfo(publicKey));
        //}

        private static void VerifyArguments(XmlSignatureAppearance sap, IExternalSignature externalSignature) {
            if (sap.GetXmlLocator() == null)
                throw new DocumentException(MessageLocalization.GetComposedMessage("xmllocator.cannot.be.null"));
            if (!externalSignature.GetHashAlgorithm().Equals(SecurityConstants.SHA1))
                throw new UnsupportedPdfException(MessageLocalization.GetComposedMessage("support.only.sha1.hash.algorithm"));

            if (!externalSignature.GetEncryptionAlgorithm().Equals(SecurityConstants.RSA)
                && !externalSignature.GetEncryptionAlgorithm().Equals(SecurityConstants.DSA))
                throw new UnsupportedPdfException(MessageLocalization.GetComposedMessage("support.only.rsa.and.dsa.algorithms"));
        }
예제 #21
0
파일: TedaSign.cs 프로젝트: page2me/TeDA
        public byte[] signPdf(byte[] inputPdf, byte[] sigImg, string signatureField)
        {
            this.getCRLList();
            Console.WriteLine("Read PDF");
            PdfReader    reader = new PdfReader(inputPdf);
            MemoryStream output = new MemoryStream();

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

            PdfSignatureAppearance sap = stamper.SignatureAppearance;

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

            sap.CertificationLevel = PdfSignatureAppearance.NOT_CERTIFIED;

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

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


            return(output.ToArray());
        }
예제 #22
0
        /**
         * Signs the document using the detached mode, CMS or CAdES equivalent.
         * @param sap the PdfSignatureAppearance
         * @param externalSignature the interface providing the actual signing
         * @param chain the certificate chain
         * @param crlList the CRL list
         * @param ocspClient the OCSP client
         * @param tsaClient the Timestamp client
         * @param provider the provider or null
         * @param estimatedSize the reserved size for the signature. It will be estimated if 0
         * @param cades true to sign CAdES equivalent PAdES-BES, false to sign CMS
         * @throws DocumentException
         * @throws IOException
         * @throws GeneralSecurityException
         * @throws NoSuchAlgorithmException
         * @throws Exception
         */
        public static void SignDetached(PdfSignatureAppearance sap, IExternalSignature externalSignature, ICollection <X509Certificate> chain, ICollection <ICrlClient> crlList, IOcspClient ocspClient,
                                        ITSAClient tsaClient, int estimatedSize, CryptoStandard sigtype)
        {
            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);
        }
예제 #23
0
        /// <summary>Signs the document using the detached mode, CMS or CAdES equivalent.</summary>
        /// <remarks>
        /// Signs the document using the detached mode, CMS or CAdES equivalent.
        /// <br /><br />
        /// NOTE: This method closes the underlying pdf document. This means, that current instance
        /// of PdfSigner cannot be used after this method call.
        /// </remarks>
        /// <param name="externalSignature">the interface providing the actual signing</param>
        /// <param name="chain">the certificate chain</param>
        /// <param name="crlList">the CRL list</param>
        /// <param name="ocspClient">the OCSP client</param>
        /// <param name="tsaClient">the Timestamp client</param>
        /// <param name="externalDigest">an implementation that provides the digest</param>
        /// <param name="estimatedSize">the reserved size for the signature. It will be estimated if 0</param>
        /// <param name="sigtype">Either Signature.CMS or Signature.CADES</param>
        /// <exception cref="System.IO.IOException"/>
        /// <exception cref="Org.BouncyCastle.Security.GeneralSecurityException"/>
        public virtual void SignDetached(IExternalSignature externalSignature, X509Certificate[] chain, ICollection
                                         <ICrlClient> crlList, IOcspClient ocspClient, ITSAClient tsaClient, int estimatedSize, PdfSigner.CryptoStandard
                                         sigtype)
        {
            if (closed)
            {
                throw new PdfException(PdfException.ThisInstanceOfPdfSignerAlreadyClosed);
            }
            ICollection <byte[]> crlBytes = null;
            int i = 0;

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

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

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

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

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

            dic2.Put(PdfName.Contents, new PdfString(paddedSig).SetHexWriting(true));
            Close(dic2);
            closed = true;
        }
예제 #24
0
        public static byte[] Sign(IExternalSignature externalSignature, X509Certificate[] certChain, string src, string friendlyName, string subject, string sourceName, string documentLink, string documentName)
        {
            int numberOfSignatures = 0;
            int numberOfPages      = 0;

            using (PdfReader reader = new PdfReader(src))
            {
                using (PdfDocument pdf = new PdfDocument(reader))
                {
                    numberOfPages = pdf.GetNumberOfPages();

                    PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf, false);
                    if (form != null)
                    {
                        foreach (var field in form.GetFormFields())
                        {
                            if (field.Value is iText.Forms.Fields.PdfSignatureFormField)
                            {
                                numberOfSignatures++;
                            }
                        }
                    }
                }
            }

            if (numberOfSignatures == 0)
            {
                string hash = GetMD5HashFromFile(src);

                src            = AddPage(src, sourceName, documentLink, documentName, hash);
                numberOfPages += 1;
            }

            float posSignY = 615 - (numberOfSignatures * 70);

            using (PdfReader reader = new PdfReader(src))
            {
                StampingProperties stampingProperties = new StampingProperties();
                stampingProperties.UseAppendMode();

                using (MemoryStream ms = new MemoryStream())
                {
                    PdfSigner signer =
                        new PdfSigner(reader, ms, stampingProperties);

                    Rectangle rect = new Rectangle(36, posSignY, 520, 65);

                    PdfSignatureAppearance appearance = signer.GetSignatureAppearance();
                    appearance
                    .SetPageRect(rect)
                    .SetPageNumber(numberOfPages)
                    .SetCertificate(certChain[0]);

                    PdfFormXObject n2     = appearance.GetLayer2();
                    Canvas         canvas = new Canvas(n2, signer.GetDocument());

                    canvas.Add(new Paragraph(friendlyName).SetMargin(0));
                    canvas.Add(new Paragraph("Assinado digitalmente por: " + friendlyName).SetFontSize(10).SetMargin(0));
                    canvas.Add(new Paragraph("Data: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss \"GMT\"zzz")).SetFontSize(10).SetMargin(0));
                    canvas.Add(new Paragraph("Subject: " + subject).SetFontSize(10).SetMargin(0));

                    signer.SignDetached(externalSignature, certChain, null, null, null, 0,
                                        PdfSigner.CryptoStandard.CADES);

                    return(ms.ToArray());
                }
            }
        }
예제 #25
0
 /**
  * Signs the document using the detached mode, CMS or CAdES equivalent.
  * @param sap the PdfSignatureAppearance
  * @param externalSignature the interface providing the actual signing
  * @param chain the certificate chain
  * @param crlList the CRL list
  * @param ocspClient the OCSP client
  * @param tsaClient the Timestamp client
  * @param provider the provider or null
  * @param estimatedSize the reserved size for the signature. It will be estimated if 0
  * @param cades true to sign CAdES equivalent PAdES-BES, false to sign CMS
  * @throws DocumentException
  * @throws IOException
  * @throws GeneralSecurityException
  * @throws NoSuchAlgorithmException
  * @throws Exception
  */
 public static void SignDetached(PdfSignatureAppearance sap, IExternalSignature externalSignature,
                                 ICollection <X509Certificate> chain, ICollection <ICrlClient> crlList, IOcspClient ocspClient,
                                 ITSAClient tsaClient, int estimatedSize, CryptoStandard sigtype)
 {
     SignDetached(sap, externalSignature, chain, crlList, ocspClient, tsaClient, estimatedSize, sigtype, (SignaturePolicyIdentifier)null);
 }
예제 #26
0
        /**
         * Signs the xml with XAdES BES using the enveloped mode, with optional xpath transform (see XmlSignatureAppearance).
         * @param sap the XmlSignatureAppearance
         * @param externalSignature  the interface providing the actual signing
         * @param chain the certificate chain
         * @param includeSignaturePolicy if true SignaturePolicyIdentifier will be included (XAdES-EPES)
         * @throws GeneralSecurityException
         * @throws IOException
         * @throws DocumentException
         */
        public static void SignXades(XmlSignatureAppearance sap, IExternalSignature externalSignature, X509Certificate[] chain,
            bool includeSignaturePolicy) {

            VerifyArguments(sap, externalSignature);
            String contentReferenceId = SecurityConstants.Reference_ + GetRandomId();
            String signedPropertiesId = SecurityConstants.SignedProperties_ + GetRandomId();
            String signatureId = SecurityConstants.Signature_ + GetRandomId();

            XmlDocument doc = sap.GetXmlLocator().GetDocument();
            KeyInfoClause keyInfo = GenerateKeyInfo(chain, sap);
            List<XmlElement> references = new List<XmlElement>(2);
            
            XmlElement signature = GenerateSignatureElement(sap.GetXmlLocator(), signatureId, true);
            String[] signaturePolicy = null;
            if(includeSignaturePolicy) {
                signaturePolicy = new String[2];
                if(externalSignature.GetEncryptionAlgorithm().Equals(SecurityConstants.RSA)) {
                    signaturePolicy[0] = SecurityConstants.OID_RSA_SHA1;
                    signaturePolicy[1] = SecurityConstants.OID_RSA_SHA1_DESC;
                }
                else {
                    signaturePolicy[0] = SecurityConstants.OID_DSA_SHA1;
                    signaturePolicy[1] = SecurityConstants.OID_DSA_SHA1_DESC;
                }
            }

            XmlElement signedProperty;
            XmlElement dsObject = GenerateXadesObject(sap, signatureId, contentReferenceId, signedPropertiesId, signaturePolicy, out signedProperty);
            
            references.Add(GenerateCustomReference(doc, signedProperty, "#" + signedPropertiesId, SecurityConstants.SignedProperties_Type, null));
            references.Add(GenerateContentReference(doc, sap, contentReferenceId));

            Sign(signature, sap.GetXmlLocator(), externalSignature, references, dsObject, keyInfo);

            sap.Close();
        }
        public static byte[] AssinarPdf(X509Certificate2 certificate, DadosAssinatura dadosAssinatura)
        {
            try
            {
                // ler arquivo e insere dados de assinatura
                using (PdfReader reader = new PdfReader(dadosAssinatura.ArquivoPdf))
                {
                    using (MemoryStream fout = new MemoryStream())
                    {
                        PdfStamper stamper = PdfStamper.CreateSignature(reader, fout, '\0');

                        // texto marca d'água
                        Font     f         = new Font(Font.FontFamily.UNDEFINED, 10);
                        Phrase   pAssinado = new Phrase("Assinado digitalmente por:", f);
                        string[] dados     = certificate.GetNameInfo(X509NameType.SimpleName, false).Split(':');

                        Phrase pNome      = new Phrase(dados[0], f);
                        Phrase pDocumento = new Phrase(dados[1], f);
                        Phrase pData      = new Phrase(certificate.GetEffectiveDateString(), f);
                        Phrase pServico   = new Phrase(dadosAssinatura.Servico, f);
                        // Imagem marca d'água
                        Image img = dadosAssinatura.Imagem;
                        float w   = 200F;
                        float h   = 75.2F;
                        // Transparência
                        PdfGState gs1 = new PdfGState();

                        // Propriedades
                        PdfContentByte over;
                        Rectangle      pagesize;

                        int n = reader.NumberOfPages;

                        //Página
                        var pagina = 1;
                        pagesize = reader.GetPageSizeWithRotation(pagina);


                        switch (dadosAssinatura.PaginaAssinatura)
                        {
                        case EnumPaginaAssinatura.PRIMEIRA:
                            pagina = 1;
                            break;

                        case EnumPaginaAssinatura.ULTIMA:
                            pagina = reader.NumberOfPages;
                            break;

                        default:
                            pagina = 1;
                            break;
                        }
                        float x, y, xr = 0, hr = 0, yr = 0, wr = 0;
                        //Posição da assinatura
                        switch (dadosAssinatura.Posicao)
                        {
                        case EnumPosicao.ACIMA_ESQUERDA:
                            x  = (float)(pagesize.Left * 0.88);
                            y  = (float)(pagesize.Top * 0.88);
                            xr = x * 0.5F;
                            wr = w;
                            yr = pagesize.Top * 0.97F;
                            hr = pagesize.Top * 0.88F;

                            break;

                        case EnumPosicao.ACIMA_DIREITA:
                            x  = (float)(pagesize.Right * 0.64);
                            y  = (float)(pagesize.Top * 0.88);
                            xr = pagesize.Right * 0.97F;
                            wr = xr - w;
                            yr = pagesize.Top * 0.97F;
                            hr = pagesize.Top * 0.88F;
                            break;

                        case EnumPosicao.ABAIXO_ESQUERDA:
                            x  = (float)(pagesize.Left * 0.88);
                            y  = (float)(pagesize.Bottom * 0.88);
                            xr = x * 0.5F;
                            wr = w;
                            yr = y;
                            hr = h;
                            break;

                        case EnumPosicao.ABAIXO_DIREITA:
                            x  = (float)(pagesize.Right * 0.64);
                            y  = (float)(pagesize.Bottom * 0.88);
                            xr = x * 1.53F;
                            wr = w * 1.9F;
                            yr = y;
                            hr = h;
                            break;

                        default:
                            x  = (float)(pagesize.Left * 0.88);
                            y  = (float)(pagesize.Top * 0.88);
                            xr = x * 1.53F;
                            wr = w * 1.9F;
                            break;
                        }

                        //Plota a assinatura no pdf
                        over = stamper.GetOverContent(pagina);
                        over.SaveState();
                        over.SetGState(gs1);
                        over.AddImage(img, w, 0, 0, h, x, y);
                        ColumnText.ShowTextAligned(over, Element.ALIGN_TOP, pAssinado, x + 10, y + 60, 0);
                        ColumnText.ShowTextAligned(over, Element.ALIGN_TOP, pNome, x + 10, y + 50, 0);
                        ColumnText.ShowTextAligned(over, Element.ALIGN_TOP, pDocumento, x + 10, y + 40, 0);
                        ColumnText.ShowTextAligned(over, Element.ALIGN_TOP, pData, x + 10, y + 25, 0);
                        ColumnText.ShowTextAligned(over, Element.ALIGN_TOP, pServico, x + 10, y + 10, 0);
                        over.RestoreState();

                        PdfSignatureAppearance appearance = stamper.SignatureAppearance;
                        appearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION;
                        appearance.Layer2Text             = "";
                        appearance.Layer4Text             = "";
                        Rectangle rect = new Rectangle(wr, hr, xr, yr);
                        appearance.SetVisibleSignature(rect, pagina, "Assinatura Digital");

                        ICollection <Org.BouncyCastle.X509.X509Certificate> certChain;
                        IExternalSignature es = ResolveExternalSignatureFromCertStore(certificate, dadosAssinatura.CertificadoValido, out certChain);

                        //Autenticação da assinatura digital
                        MakeSignature.SignDetached(appearance, es, certChain, null, null, null, 0, CryptoStandard.CADES);

                        stamper.Close();
                        return(fout.ToArray());
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.TraceError("Erro durante assinatura digital do pdf: {0}", ex.Message);
                throw;
            }
        }
예제 #28
0
 /**
  * Signs the xml using the enveloped mode, with optional xpath transform (see XmlSignatureAppearance).
  * @param sap the XmlSignatureAppearance
  * @param externalSignature  the interface providing the actual signing
  * @param chain the certificate chain
  * @throws GeneralSecurityException
  * @throws IOException
  * @throws DocumentException
  */
 public static void SignXmlDSig(XmlSignatureAppearance sap,
                                IExternalSignature externalSignature, X509Certificate[] chain)
 {
     SignXmlDSig(sap, externalSignature, new KeyInfoX509Data(chain[0].GetEncoded()));
 }
예제 #29
0
 /**
  * Signs the xml using the enveloped mode, with optional xpath transform (see XmlSignatureAppearance).
  * @param sap the XmlSignatureAppearance
  * @param externalSignature  the interface providing the actual signing
  * @param publicKey PublicKey for verification
  * @throws GeneralSecurityException
  * @throws IOException
  * @throws DocumentException
  */
 public static void SignXmlDSig(XmlSignatureAppearance sap,
                                IExternalSignature externalSignature, AsymmetricAlgorithm publicKey)
 {
     SignXmlDSig(sap, externalSignature, GenerateKeyInfo(publicKey));
 }
예제 #30
0
 /**
  * Signs the xml with XAdES BES using the enveloped mode, with optional xpath transform (see XmlSignatureAppearance).
  * @param sap the XmlSignatureAppearance
  * @param externalSignature  the interface providing the actual signing
  * @param chain the certificate chain
  * @throws GeneralSecurityException
  * @throws IOException
  * @throws DocumentException
  */
 public static void SignXadesEpes(XmlSignatureAppearance sap, IExternalSignature externalSignature, X509Certificate[] chain) {
     SignXades(sap, externalSignature, chain, true);
 }
예제 #31
0
        private static void Sign(XmlElement signature, IXmlLocator xmlLocator, IExternalSignature externalSignature,
                                 List <XmlElement> references, XmlElement dsObject, KeyInfoClause keyInfo)
        {
            XmlDocument originalDoc = xmlLocator.GetDocument();

            if (signature == null)
            {
                throw new InvalidOperationException();
            }

            XmlElement signedInfo = originalDoc.CreateElement("SignedInfo", SecurityConstants.XMLDSIG_URI);

            signature.AppendChild(signedInfo);

            XmlElement canonicalizationMethod = originalDoc.CreateElement("CanonicalizationMethod", SecurityConstants.XMLDSIG_URI);

            canonicalizationMethod.SetAttribute("Algorithm", SecurityConstants.XMLDSIG_URI_C14N);
            signedInfo.AppendChild(canonicalizationMethod);

            XmlElement signatureMethod = originalDoc.CreateElement("SignatureMethod", SecurityConstants.XMLDSIG_URI);

            if (externalSignature.GetEncryptionAlgorithm().Equals(SecurityConstants.RSA))
            {
                signatureMethod.SetAttribute("Algorithm", SecurityConstants.XMLDSIG_URI_RSA_SHA1);
            }
            else if (externalSignature.GetEncryptionAlgorithm().Equals(SecurityConstants.DSA))
            {
                signatureMethod.SetAttribute("Algorithm", SecurityConstants.XMLDSIG_URI_DSA_SHA1);
            }
            signedInfo.AppendChild(signatureMethod);

            foreach (XmlElement reference in references)
            {
                signedInfo.AppendChild(reference);
            }

            //if append Signature to original document upper - reference digest will be incorrect.
            originalDoc.DocumentElement.AppendChild(signature);

            XmlElement signedInfoDigest = (XmlElement)signedInfo.CloneNode(true);

            NormalizeNamespaces(signedInfo.CreateNavigator(), signedInfoDigest.CreateNavigator());
            XmlDocument signedInfoDoc = new XmlDocument(originalDoc.NameTable);

            signedInfoDoc.LoadXml(signedInfoDigest.OuterXml);
            byte[] byteRange = CalculateC14nByteRange(signedInfoDoc);

            //Sign with ExternalSignature
            String valueBase64 = Convert.ToBase64String(externalSignature.Sign(byteRange));

            XmlElement signatureValue = originalDoc.CreateElement("SignatureValue", SecurityConstants.XMLDSIG_URI);

            signatureValue.AppendChild(originalDoc.CreateTextNode(valueBase64));

            signature.AppendChild(signatureValue);

            if (keyInfo != null)
            {
                XmlElement keyInfoElement = originalDoc.CreateElement("KeyInfo", SecurityConstants.XMLDSIG_URI);
                keyInfoElement.AppendChild(originalDoc.ImportNode(keyInfo.GetXml(), true));
                signature.AppendChild(keyInfoElement);
            }

            if (dsObject != null)
            {
                signature.AppendChild(dsObject);
            }

            xmlLocator.SetDocument(originalDoc);
        }
예제 #32
0
 /**
  * Signs the xml using the enveloped mode, with optional xpath transform (see XmlSignatureAppearance).
  * @param sap the XmlSignatureAppearance
  * @param externalSignature  the interface providing the actual signing
  * @param chain the certificate chain
  * @throws GeneralSecurityException
  * @throws IOException
  * @throws DocumentException
  */
 public static void SignXmlDSig(XmlSignatureAppearance sap,
     IExternalSignature externalSignature, X509Certificate[] chain) {
     SignXmlDSig(sap, externalSignature, new KeyInfoX509Data(chain[0].GetEncoded()));
 }
예제 #33
0
 /**
  * Signs the xml using the enveloped mode, with optional xpath transform (see XmlSignatureAppearance).
  * @param sap the XmlSignatureAppearance
  * @param externalSignature  the interface providing the actual signing
  * @param publicKey PublicKey for verification
  * @throws GeneralSecurityException
  * @throws IOException
  * @throws DocumentException
  */
 public static void SignXmlDSig(XmlSignatureAppearance sap,
     IExternalSignature externalSignature, AsymmetricAlgorithm publicKey) {
     SignXmlDSig(sap, externalSignature, GenerateKeyInfo(publicKey));
 }
예제 #34
0
        private static void Sign(XmlElement signature, IXmlLocator xmlLocator, IExternalSignature externalSignature, 
                                 List<XmlElement> references, XmlElement dsObject, KeyInfoClause keyInfo) {

            XmlDocument originalDoc = xmlLocator.GetDocument();

            if (signature == null)
                throw new InvalidOperationException();

            XmlElement signedInfo = originalDoc.CreateElement("SignedInfo", SecurityConstants.XMLDSIG_URI);
            signature.AppendChild(signedInfo);

            XmlElement canonicalizationMethod = originalDoc.CreateElement("CanonicalizationMethod", SecurityConstants.XMLDSIG_URI);
            canonicalizationMethod.SetAttribute("Algorithm", SecurityConstants.XMLDSIG_URI_C14N);
            signedInfo.AppendChild(canonicalizationMethod);

            XmlElement signatureMethod = originalDoc.CreateElement("SignatureMethod", SecurityConstants.XMLDSIG_URI);
            if(externalSignature.GetEncryptionAlgorithm().Equals(SecurityConstants.RSA))
                signatureMethod.SetAttribute("Algorithm", SecurityConstants.XMLDSIG_URI_RSA_SHA1);
            else if(externalSignature.GetEncryptionAlgorithm().Equals(SecurityConstants.DSA))
                signatureMethod.SetAttribute("Algorithm", SecurityConstants.XMLDSIG_URI_DSA_SHA1);
            signedInfo.AppendChild(signatureMethod);

            foreach (XmlElement reference in references)
                signedInfo.AppendChild(reference);    
            
            //if append Signature to original document upper - reference digest will be incorrect.
            originalDoc.DocumentElement.AppendChild(signature);

            XmlElement signedInfoDigest = (XmlElement)signedInfo.CloneNode(true);
            NormalizeNamespaces(signedInfo.CreateNavigator(), signedInfoDigest.CreateNavigator());
            XmlDocument signedInfoDoc = new XmlDocument(originalDoc.NameTable);
            signedInfoDoc.LoadXml(signedInfoDigest.OuterXml);
            byte[] byteRange = CalculateC14nByteRange(signedInfoDoc);

            //Sign with ExternalSignature
            String valueBase64 = Convert.ToBase64String(externalSignature.Sign(byteRange));

            XmlElement signatureValue = originalDoc.CreateElement("SignatureValue", SecurityConstants.XMLDSIG_URI);
            signatureValue.AppendChild(originalDoc.CreateTextNode(valueBase64));

            signature.AppendChild(signatureValue);

            if(keyInfo != null) {
                XmlElement keyInfoElement = originalDoc.CreateElement("KeyInfo", SecurityConstants.XMLDSIG_URI);
                keyInfoElement.AppendChild(originalDoc.ImportNode(keyInfo.GetXml(), true));
                signature.AppendChild(keyInfoElement);
            }

            if (dsObject != null)
                signature.AppendChild(dsObject);

            xmlLocator.SetDocument(originalDoc);
        }
예제 #35
0
 /**
  * Signs the xml using the enveloped mode, with optional xpath transform (see XmlSignatureAppearance).
  * @param sap the XmlSignatureAppearance
  * @param externalSignature  the interface providing the actual signing
  * @param publicKey PublicKey for verification
  * @throws GeneralSecurityException
  * @throws IOException
  * @throws DocumentException
  */
 public static void signXmlDSig(XmlSignatureAppearance sap,
                                IExternalSignature externalSignature, PublicKey publicKey)
 {
     throw new NotImplementedException("Xml signatures are not supported yet");
 }
예제 #36
0
        //public static void AssinaComToken_OLD(string FileName, string SignFileName, X509Certificate2 cert, float X, float Y, int Pagina, double Escala, bool SeloCargo = false, bool SeloCREA = false, bool SeloCRM = false, string Cargo = "", string CREACRM = "", bool AddTimeStamper = true, string urlTimeStamper = "https://freetsa.org/tsr", string timeStampUser = "", string timeStampPass = "", string Reason = "Assinatura Digital", bool AplicaPolitica = false, string MyDigestAlgorithm = "SHA-1", string Contact = "", string Location = "Indústrias Nucleares do Brasil S/A - INB", string Creator = "Assinador da INB", bool SeloCertifico = false)
        //{
        //    string SourcePdfFileName = FileName;
        //    string DestPdfFileName = SignFileName;
        //    int Largura = 155;
        //    int Altura = 63;
        //    Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser();
        //    Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(cert.RawData) };
        //    IExternalSignature externalSignature = new X509Certificate2Signature(cert, MyDigestAlgorithm);
        //    PdfReader pdfReader = new PdfReader(SourcePdfFileName);
        //    FileStream signedPdf = new FileStream(DestPdfFileName, FileMode.Create, FileAccess.ReadWrite);  //the output pdf file
        //                                                                                                    //cria a assinatura
        //    PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0', "temp" + signedPdf, true);
        //    PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance;
        //    Bitmap bmp = INB.Assinador.Helper.Graphic.ConfiguraBMP(cert, SeloCargo, SeloCREA, SeloCRM, Cargo, CREACRM, out Altura, SeloCertifico);

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

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

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

        public static void AssinaComToken(string FileName, string SignFileName, CertSimples cert, float X, float Y, int Pagina, int Rotation, bool AddTimeStamper = true, string urlTimeStamper = "https://freetsa.org/tsr", string timeStampUser = "", string timeStampPass = "", string Reason = "Assinatura Digital", bool AplicaPolitica = false, string MyDigestAlgorithm = "SHA-1", string Contact = "", string Location = "Indústrias Nucleares do Brasil S/A - INB", string Creator = "Assinador da INB", TipoAssinatura Tipo = TipoAssinatura.Normal, string Cargo = "", string CREACRM = "")
        {
            string SourcePdfFileName = FileName;
            string DestPdfFileName   = SignFileName;
            int    Largura           = 155;
            int    Altura            = 63;

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

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


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

            RSACryptoServiceProvider rsa;
            RSACryptoServiceProvider Provider;
            IExternalSignature       externalSignature = null;


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

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

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

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

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

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

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

            crlList.Add(new CrlClientOnline(chain));

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