/**
         * 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);
        }
예제 #2
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.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 = 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);
        }
예제 #3
0
        public static void signPdfFile(string sourceDocument, string destinationPath, Stream privateKeyStream, string keyPassword, string reason, string location)
        {
            Pkcs12Store pk12 = new Pkcs12Store(privateKeyStream, keyPassword.ToCharArray());

            privateKeyStream.Dispose();

            //then Iterate throught certificate entries to find the private key entry
            string alias = null;

            foreach (string tAlias in pk12.Aliases)
            {
                if (pk12.IsKeyEntry(tAlias))
                {
                    alias = tAlias;
                    break;
                }
            }
            var pk    = pk12.GetKey(alias).Key;
            var ce    = pk12.GetCertificateChain(alias);
            var chain = new X509Certificate[ce.Length];

            for (int k = 0; k < ce.Length; ++k)
            {
                chain[k] = ce[k].Certificate;
            }
            // reader and stamper
            PdfReader  reader = new PdfReader(sourceDocument);
            FileStream fout   = new FileStream(destinationPath, FileMode.Create, FileAccess.ReadWrite);


            PdfStamper             stamper    = PdfStamper.CreateSignature(reader, fout, '\0', null, true);
            PdfSignatureAppearance appearance = stamper.SignatureAppearance;

            appearance.SetCrypto(pk, chain, null, PdfSignatureAppearance.SELF_SIGNED);
            appearance.Reason   = reason;
            appearance.Location = location;

            stamper.Close();
        }
예제 #4
0
        /// <summary>
        /// Signs a PDF document using iTextSharp library
        /// </summary>
        /// <param name="sourceDocument">The path of the source pdf document which is to be signed</param>
        /// <param name="destinationDocument">The path at which the signed pdf document should be generated</param>
        /// <param name="privateKeyStream">A Stream containing the private/public key in .pfx format which would be used to sign the document</param>
        /// <param name="pfxKeyPass">The password for the private key</param>
        /// <param name="reasonForSigning">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>
        public static void SignPdfFile(string sourceDocument, string destinationDocument, SignInfo i)
        {
            using (var cpfxFile = new FileStream(i.pfxFilePath, FileMode.Open, FileAccess.Read))
            {
                Pkcs12Store pk12 = new Pkcs12Store(cpfxFile, i.pfxKeyPass.ToCharArray());

                string alias = null;

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

                var pk = pk12.GetKey(alias).Key;
                using (var reader = new PdfReader(sourceDocument))
                    using (var fout = new FileStream(destinationDocument, FileMode.Create, FileAccess.ReadWrite))
                        using (var stamper = PdfStamper.CreateSignature(reader, fout, '\0'))
                        {
                            stamper.SetEncryption(i.docPass, i.docPass, PdfWriter.ALLOW_SCREENREADERS, PdfWriter.STRENGTH128BITS);

                            var img = new iTextSharp.text.Jpeg(new Uri(i.signImagePath));
                            PdfSignatureAppearance appearance = stamper.SignatureAppearance;
                            appearance.Image    = img;
                            appearance.Reason   = i.reasonForSigning;
                            appearance.Location = i.location;
                            const float x = 20, y = 10;
                            appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(x, y, x + img.Width, y + img.Width), 1, "Icsi-Vendor");

                            IExternalSignature es = new PrivateKeySignature(pk, "SHA-256");
                            MakeSignature.SignDetached(appearance, es,
                                                       new X509Certificate[] { pk12.GetCertificate(alias).Certificate }, null, null, null, 0, CryptoStandard.CMS);
                            stamper.Close();
                        }
            }
        }
예제 #5
0
        public PdfSignatureAppearance makePdfSignature(PdfSignatureAppearance signatureAppearance, DesignSign design)
        {
            /* signatureAppearance.Layer2Text =
             *  "K\x00fd bởi: " + this.getSubjectByKey("CN") +
             *  "\nK\x00fd ng\x00e0y: " + string.Format("{0:d/M/yyyy HH:mm:ss}"+
             *  "\nMã số thuế:"+this.getMST_EX()
             *  , DateTime.Now);
             */
            // iTextSharp.text.Font font2 = new iTextSharp.text.Font(BaseFont.CreateFont(@"D:\C++Project\Projects\times.ttf", "Identity-H", false));
            //    iTextSharp.text.Font font2 = new iTextSharp.text.Font(BaseFont.CreateFont("Tahoma", "UTF-8", false));

            signatureAppearance.Location = design.getLocation();
            signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION;
            signatureAppearance.SignDate   = DateTime.Now;
            signatureAppearance.Layer2Font = design.getFont();
            signatureAppearance.Layer2Font.SetColor(design.getColor().r, design.getColor().g, design.getColor().b);

            //  signatureAppearance.SetVisibleSignature(design.getRect(),design.getPage(), null);


            return(signatureAppearance);
        }
예제 #6
0
        private static void CertSign(X509Certificate2 cert, X509CertificateParser cp, string destinationPath, PdfReader reader, string reason, string location)
        {
            Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[]
            {
                cp.ReadCertificate(cert.RawData)
            };

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

            using (FileStream fout = new FileStream(destinationPath, FileMode.Create, FileAccess.ReadWrite))
            {
                using (PdfStamper stamper = PdfStamper.CreateSignature(reader, fout, '\0', null, true))
                {
                    PdfSignatureAppearance appearance = stamper.SignatureAppearance;
                    appearance.Reason   = reason;
                    appearance.Location = location;
                    MakeSignature.SignDetached(appearance, externalSignature, chain, null, null, null, 0,
                                               CryptoStandard.CADES);
                    stamper.Close();
                }
            }
        }
        public void Sign3(String src, String name, String dest, X509Certificate[] chain,
                          ICipherParameters pk, String digestAlgorithm, PdfSigner.CryptoStandard subfilter,
                          String reason, String location)
        {
            PdfReader reader = new PdfReader(src);
            PdfSigner signer = new PdfSigner(reader, new FileStream(dest, FileMode.Create), new StampingProperties());

            PdfSignatureAppearance appearance = signer.GetSignatureAppearance();

            appearance.SetReason(reason);
            appearance.SetLocation(location);
            signer.SetFieldName(name);

            // Set a custom text and background image
            appearance.SetLayer2Text("This document was signed by Bruno Specimen");
            appearance.SetImage(ImageDataFactory.Create(IMG));
            appearance.SetImageScale(1);

            PrivateKeySignature pks = new PrivateKeySignature(pk, digestAlgorithm);

            signer.SignDetached(pks, chain, null, null, null, 0, subfilter);
        }
예제 #8
0
        public void Sign3(String src, String name, String dest, ICollection <X509Certificate> chain, ICipherParameters pk,
                          String digestAlgorithm, CryptoStandard subfilter, String reason, String location)
        {
            // Creating the reader and the stamper
            PdfReader  reader  = new PdfReader(src);
            FileStream os      = new FileStream(dest, FileMode.Create);
            PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0');
            // Creating the appearance
            PdfSignatureAppearance appearance = stamper.SignatureAppearance;

            appearance.Reason   = reason;
            appearance.Location = location;
            appearance.SetVisibleSignature(name);
            // Custom text and background image
            appearance.Layer2Text = "This document was signed by Bruno Specimen";
            appearance.Image      = Image.GetInstance(IMG);
            appearance.ImageScale = 1;
            // Creating the signature
            IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm);

            MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, subfilter);
        }
예제 #9
0
        public void Sign2(String src, String name, String dest, ICollection <X509Certificate> chain, ICipherParameters pk,
                          String digestAlgorithm, CryptoStandard subfilter, String reason, String location)
        {
            // Creating the reader and the stamper
            PdfReader  reader  = new PdfReader(src);
            FileStream os      = new FileStream(dest, FileMode.Create);
            PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0');
            // Creating the appearance
            PdfSignatureAppearance appearance = stamper.SignatureAppearance;

            appearance.Reason   = reason;
            appearance.Location = location;
            appearance.SetVisibleSignature(name);
            // Custom text, custom font, and right-to-left writing
            appearance.Layer2Text   = "\u0644\u0648\u0631\u0627\u0646\u0633 \u0627\u0644\u0639\u0631\u0628";
            appearance.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
            appearance.Layer2Font   = new Font(BaseFont.CreateFont("C:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 12);
            // Creating the signature
            IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm);

            MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, subfilter);
        }
예제 #10
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);
        }
예제 #11
0
        /// <summary>
        /// Methods which returns base64 digested PDF.
        /// </summary>
        /// <param name="unsignedPdf">Path to pdf which needs to be signed</param>
        /// <param name="tempPdf">Path to temporary pdf</param>
        /// <param name="signatureFieldName">Name of field</param>
        /// <returns></returns>
        public static string GetBytesToSign(string unsignedPdf, string tempPdf, string signatureFieldName)
        {
            if (File.Exists(tempPdf))
            {
                File.Delete(tempPdf);
            }

            using (PdfReader reader = new PdfReader(unsignedPdf))
            {
                using (FileStream os = File.OpenWrite(tempPdf))
                {
                    StampingProperties sp = new StampingProperties();
                    sp.UseAppendMode();

                    PdfSigner pdfSigner = new PdfSigner(reader, os, sp);
                    pdfSigner.SetFieldName(signatureFieldName);

                    PdfSignatureAppearance appearance = pdfSigner.GetSignatureAppearance();
                    appearance.SetPageNumber(1);
                    appearance.SetPageRect(new Rectangle(100, 100));
                    appearance.SetLocation("Varazdin");

                    //Creating container for emty signature, with atrivute where digest is calculated.
                    //ExternalHashingSignatureContainer external = new ExternalHashingSignatureContainer(PdfName.Adobe_PPKLite, PdfName.Adbe_pkcs7_detached);
                    //pdfSigner.SignExternalContainer(external, 8192);
                    //hash = external.Hash;

                    //Creating container for empty signature.
                    IExternalSignatureContainer external = new ExternalBlankSignatureContainer(PdfName.Adobe_PPKLite, PdfName.Adbe_x509_rsa_sha1);
                    pdfSigner.SignExternalContainer(external, 8192);

                    //Digest from created new temporary PDF with empty space for signature.
                    FileStream oso = File.OpenRead(temp);
                    hash = DigestAlgorithms.Digest(oso, DigestAlgorithms.SHA256);

                    return(Convert.ToBase64String(hash));
                }
            }
        }
예제 #12
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);
        }
        public void Sign(String src, String dest, X509Certificate[] chain, PdfSigner.CryptoStandard subfilter,
                         String reason, String location)
        {
            PdfReader reader = new PdfReader(src);
            PdfSigner signer = new PdfSigner(reader, new FileStream(dest, FileMode.Create), new StampingProperties());

            // Create the signature appearance
            Rectangle rect = new Rectangle(36, 648, 200, 100);
            PdfSignatureAppearance appearance = signer.GetSignatureAppearance();

            appearance
            .SetReason(reason)
            .SetLocation(location)
            .SetPageRect(rect)
            .SetPageNumber(1);
            signer.SetFieldName("sig");

            IExternalSignature pks = new ServerSignature();

            // Sign the document using the detached mode, CMS or CAdES equivalent.
            signer.SignDetached(pks, chain, null, null, null, 0, subfilter);
        }
예제 #14
0
        public virtual void PrepareDocForSignDeferredTest()
        {
            String    input         = sourceFolder + "helloWorldDoc.pdf";
            String    output        = destinationFolder + "newTemplateForSignDeferred.pdf";
            String    sigFieldName  = "DeferredSignature1";
            PdfName   filter        = PdfName.Adobe_PPKLite;
            PdfName   subFilter     = PdfName.Adbe_pkcs7_detached;
            int       estimatedSize = 8192;
            PdfReader reader        = new PdfReader(input);
            PdfSigner signer        = new PdfSigner(reader, new FileStream(output, FileMode.Create), new StampingProperties()
                                                    );
            PdfSignatureAppearance appearance = signer.GetSignatureAppearance();

            appearance.SetLayer2Text("Signature field which signing is deferred.").SetPageRect(new Rectangle(36, 600,
                                                                                                             200, 100)).SetPageNumber(1);
            signer.SetFieldName(sigFieldName);
            IExternalSignatureContainer external = new ExternalBlankSignatureContainer(filter, subFilter);

            signer.SignExternalContainer(external, estimatedSize);
            // validate result
            ValidateTemplateForSignedDeferredResult(output, sigFieldName, filter, subFilter, estimatedSize);
        }
예제 #15
0
        public virtual void TestSigningInAppendModeWithHybridDocument()
        {
            String    src    = sourceFolder + "hybrid.pdf";
            String    dest   = destinationFolder + "signed_hybrid.pdf";
            String    cmp    = sourceFolder + "cmp_signed_hybrid.pdf";
            PdfSigner signer = new PdfSigner(new PdfReader(src), new FileStream(dest, FileMode.Create), new StampingProperties
                                                 ().UseAppendMode());
            PdfSignatureAppearance appearance = signer.GetSignatureAppearance();

            appearance.SetLayer2FontSize(13.8f).SetPageRect(new Rectangle(36, 748, 200, 100)).SetPageNumber(1).SetReason
                ("Test").SetLocation("Nagpur");
            signer.SetFieldName("Sign1");
            signer.SetCertificationLevel(PdfSigner.NOT_CERTIFIED);
            IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256);

            signer.SignDetached(pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES);
            // Make sure iText can open the document
            new PdfDocument(new PdfReader(dest)).Close();
            // Assert that the document can be rendered correctly
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareVisually(dest, cmp, destinationFolder, "diff_", GetIgnoredAreaTestMap
                                                                                (new Rectangle(36, 748, 200, 100))));
        }
예제 #16
0
        public void Sign(String src, String name, String dest, ICollection <X509Certificate> chain, ICipherParameters pk,
                         String digestAlgorithm, CryptoStandard subfilter, String reason, String location,
                         PdfSignatureAppearance.RenderingMode renderingMode, Image image)
        {
            // Creating the reader and the stamper
            PdfReader  reader  = new PdfReader(src);
            FileStream os      = new FileStream(dest, FileMode.Create);
            PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0');
            // Creating the appearance
            PdfSignatureAppearance appearance = stamper.SignatureAppearance;

            appearance.Reason   = reason;
            appearance.Location = location;
            appearance.SetVisibleSignature(name);
            appearance.Layer2Text             = "Signed on " + DateTime.Now;
            appearance.SignatureRenderingMode = renderingMode;
            appearance.SignatureGraphic       = image;
            // Creating the signature
            IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm);

            MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, subfilter);
        }
예제 #17
0
        public void FillOutAndSign(String keystore, String src, String name, String fname, String value, String dest)
        {
            Pkcs12Store store = new Pkcs12Store(new FileStream(keystore, FileMode.Open), PASSWORD);
            String      alias = "";
            ICollection <X509Certificate> chain = new List <X509Certificate>();

            // searching for private key
            foreach (string al in store.Aliases)
            {
                if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate)
                {
                    alias = al;
                    break;
                }
            }
            AsymmetricKeyEntry pk = store.GetKey(alias);

            foreach (X509CertificateEntry c in store.GetCertificateChain(alias))
            {
                chain.Add(c.Certificate);
            }
            RsaPrivateCrtKeyParameters parameters = pk.Key as RsaPrivateCrtKeyParameters;

            PdfReader  reader  = new PdfReader(src);
            FileStream os      = new FileStream(dest, FileMode.Create);
            PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0', null, true);
            AcroFields form    = stamper.AcroFields;

            form.SetField(fname, value);
            form.SetFieldProperty(fname, "setfflags", PdfFormField.FF_READ_ONLY, null);
            // Creating the appearance
            PdfSignatureAppearance appearance = stamper.SignatureAppearance;

            appearance.SetVisibleSignature(name);
            // Creating the signature
            IExternalSignature pks = new PrivateKeySignature(parameters, "SHA-256");

            MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, CryptoStandard.CMS);
        }
        public virtual void SecondSignOfTaggedDocTest()
        {
            String signCertFileName = certsSrc + "signCertRsa01.p12";
            String outFileName      = destinationFolder + "secondSignOfTagged.pdf";
            String srcFileName      = sourceFolder + "taggedAndSignedDoc.pdf";

            X509Certificate[]  signChain      = Pkcs12FileHelper.ReadFirstChain(signCertFileName, password);
            ICipherParameters  signPrivateKey = Pkcs12FileHelper.ReadFirstKey(signCertFileName, password, password);
            IExternalSignature pks            = new PrivateKeySignature(signPrivateKey, DigestAlgorithms.SHA256);
            String             signatureName  = "Signature2";
            PdfSigner          signer         = new PdfSigner(new PdfReader(srcFileName), new FileStream(outFileName, FileMode.Create),
                                                              new StampingProperties().UseAppendMode());
            PdfDocument document = signer.GetDocument();

            document.GetWriter().SetCompressionLevel(CompressionConstants.NO_COMPRESSION);
            signer.SetFieldName(signatureName);
            PdfSignatureAppearance appearance = signer.GetSignatureAppearance();

            appearance.SetPageNumber(1);
            signer.GetSignatureAppearance().SetPageRect(new Rectangle(50, 550, 200, 100)).SetReason("Test2").SetLocation
                ("TestCity2").SetLayer2Text("Approval test signature #2.\nCreated by iText7.");
            signer.SignDetached(pks, signChain, null, null, null, 0, PdfSigner.CryptoStandard.CADES);
            PadesSigTest.BasicCheckSignedDoc(outFileName, "Signature1");
            PadesSigTest.BasicCheckSignedDoc(outFileName, "Signature2");
            using (PdfDocument twiceSigned = new PdfDocument(new PdfReader(outFileName))) {
                using (PdfDocument resource = new PdfDocument(new PdfReader(srcFileName))) {
                    float resourceStrElemNumber = resource.GetStructTreeRoot().GetPdfObject().GetAsArray(PdfName.K).GetAsDictionary
                                                      (0).GetAsArray(PdfName.K).Size();
                    float outStrElemNumber = twiceSigned.GetStructTreeRoot().GetPdfObject().GetAsArray(PdfName.K).GetAsDictionary
                                                 (0).GetAsArray(PdfName.K).Size();
                    // Here we assert the amount of objects in StructTreeRoot in resource file and twice signed file
                    // as the original signature validation failed by Adobe because of struct tree change. If the fix
                    // would make this tree unchanged, then the assertion should be adjusted with comparing the tree of
                    // objects in StructTreeRoot to ensure that it won't be changed.
                    NUnit.Framework.Assert.AreNotEqual(resourceStrElemNumber, outStrElemNumber);
                }
            }
        }
예제 #19
0
        public void Sign(String src, String name, String dest, ICollection <X509Certificate> chain, ICipherParameters pk,
                         String digestAlgorithm, CryptoStandard subfilter, String reason, String location)
        {
            // Creating the reader and the stamper
            PdfReader  reader  = new PdfReader(src);
            FileStream os      = new FileStream(dest, FileMode.Create);
            PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0');
            // Creating the appearance
            PdfSignatureAppearance appearance = stamper.SignatureAppearance;

            appearance.Reason   = reason;
            appearance.Location = location;
            appearance.SetVisibleSignature(name);
            // Creating the appearance for layer 0
            PdfTemplate n0     = appearance.GetLayer(0);
            float       x      = n0.BoundingBox.Left;
            float       y      = n0.BoundingBox.Bottom;
            float       width  = n0.BoundingBox.Width;
            float       height = n0.BoundingBox.Height;

            n0.SetColorFill(BaseColor.LIGHT_GRAY);
            n0.Rectangle(x, y, width, height);
            n0.Fill();
            // Creating the appearance for layer 2
            PdfTemplate n2 = appearance.GetLayer(2);
            ColumnText  ct = new ColumnText(n2);

            ct.SetSimpleColumn(n2.BoundingBox);
            Paragraph p = new Paragraph("This document was signed by Bruno Specimen.");

            ct.AddElement(p);
            ct.Go();
            // Creating the signature
            IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm);

            MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, subfilter);
        }
예제 #20
0
        /*public void Verify(string pdfFile, Stream fileStream)
         * {
         *
         *  //KeyStore kall = PdfPKCS7.loadCacertsKeyStore();
         *  var parser = new X509CertificateParser(fileStream);
         *  var certifi = parser.ReadCertificate ();
         *  fileStream.Dispose();
         *
         *  string pathToFiles = HttpContext.Current.Server.MapPath("~/UploadFile/output/ForCekTandaTangan.pdf");
         *  PdfReader reader = new PdfReader(pathToFiles);
         *  AcroFields af = reader.AcroFields;
         *  var names = af.GetSignatureNames();
         *  if (names.Count == 0)
         *  {
         *      System.Diagnostics.Debug.WriteLine("Tidak ada ttdnya");
         *  }
         *  else
         *  {
         *      System.Diagnostics.Debug.WriteLine("IKI lo TTD ne yooow");
         *  }
         *  foreach (string name in names)
         *  {
         *      if (!af.SignatureCoversWholeDocument(name))
         *      {
         *          System.Diagnostics.Debug.WriteLine("The signature: {0} does not covers the whole document.", name);
         *      }
         *      System.Diagnostics.Debug.WriteLine("Signature Name: " + name);
         *      System.Diagnostics.Debug.WriteLine("Signature covers whole document: " + af.SignatureCoversWholeDocument(name));
         *      System.Diagnostics.Debug.WriteLine("Document revision: " + af.GetRevision(name));
         *
         *      PdfPKCS7 pk = af.VerifySignature(name);
         *      var cal = pk.SignDate;
         *      var pkc = pk.Certificates;
         *      // TimeStampToken ts = pk.TimeStampToken;
         *      if (!pk.Verify())
         *      {
         *          System.Diagnostics.Debug.WriteLine("The signature could not be verified");
         *      } else
         *      {
         *          System.Diagnostics.Debug.WriteLine("Name signature: " + pk.SignName);
         *          System.Diagnostics.Debug.WriteLine("Reason signature: " + pk.Reason);
         *          System.Diagnostics.Debug.WriteLine("Location signature: " + pk.Location);
         *          System.Diagnostics.Debug.WriteLine("Date signature: " + pk.SignDate);
         *          System.Diagnostics.Debug.WriteLine("Version signature: " + pk.SigningInfoVersion);
         *          System.Diagnostics.Debug.WriteLine("Sertificate signature: " + pk.SigningCertificate);
         *      }
         *
         *      //IList<VerificationException>[] fails = PdfPKCS7.VerifyCertificates(pkc, new X509Certificate[] { certifi }, null, cal);
         *      //Object[] fails = PdfPKCS7.VerifyCertificates(pkc, new X509Certificate[] { }, null, cal);
         *      //if (fails != null)
         *      //{
         *      //    System.Diagnostics.Debug.WriteLine("The file is not signed using the specified key-pair.");
         *      //}
         *  }
         * }*/
        //To disable Multi signatures uncomment this line : every new signature will invalidate older ones ! line 251
        //PdfStamper st = PdfStamper.CreateSignature(reader, new FileStream(this.outputPDF, FileMode.Create, FileAccess.Write), '\0');

        public void Sign(string SigReason, string SigContact,
                         string SigLocation, string pic, bool visible, int posX, int posY)
        {
            //Activate MultiSignatures
            PdfReader  reader = new PdfReader(this.inputPDF);
            PdfStamper st     = PdfStamper.CreateSignature(reader,
                                                           new FileStream(this.outputPDF, FileMode.Create, FileAccess.Write),
                                                           '\0', null, true);

            //iTextSharp.text.Image sigImg = iTextSharp.text.Image.GetInstance(pic);
            Image sigImg = Image.GetInstance(pic);

            // MAX_WIDTH, MAX_HEIGHT
            sigImg.ScaleToFit(150, 50);
            // Set signature position on page
            sigImg.SetAbsolutePosition(posX, 840 - posY);
            // Add signatures to desired page
            PdfContentByte over = st.GetOverContent(1);

            over.AddImage(sigImg);

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

            sap.SetCrypto(this.myCert.Akp, this.myCert.Chain,
                          null, PdfSignatureAppearance.WINCER_SIGNED);
            sap.Reason   = SigReason;
            sap.Contact  = SigContact;
            sap.Location = SigLocation;
            if (visible)
            {
                sap.SetVisibleSignature(
                    new Rectangle(posX, 840 - posY, posX + 150, (840 - posY) + 50), 1, null);
            }
            st.Close();
        }
예제 #21
0
        public MemoryStream sign(
            byte[] byte_pdfData, X509Certificate2 cert, Org.BouncyCastle.X509.X509Certificate[] chain,
            string hashAlgorithm, string reason, string location, int certifyLevel,
            byte[] sigImg, bool isShowDescription
            )
        {
            //Open source PDF
            PdfReader pdfReader = new PdfReader(byte_pdfData);

            MemoryStream outputStream = new MemoryStream();

            //Create PDF Stamper
            PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, outputStream, '\0');

            //Create PDF Signature Appearance
            PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance;

            signatureAppearance.Reason                 = reason;                                           //Reason
            signatureAppearance.Location               = location;                                         //Location
            signatureAppearance.CertificationLevel     = certifyLevel;
            signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION; //Rendering mode


            IExternalSignature signature = new X509Certificate2Signature(cert, hashAlgorithm);

            try
            {
                //Do signing
                MakeSignature.SignDetached(signatureAppearance, signature, chain, null, null, null, 0, this.sigType);
            }
            catch (Exception e)
            {
                throw new Exception("Cannot sign the PDF file.", e);
            }

            return(outputStream);
        }
예제 #22
0
        public void Certify(String keystore, String src, String name, String dest)
        {
            Pkcs12Store store = new Pkcs12Store(new FileStream(keystore, FileMode.Open), PASSWORD);
            String      alias = "";
            ICollection <X509Certificate> chain = new List <X509Certificate>();

            // searching for private key
            foreach (string al in store.Aliases)
            {
                if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate)
                {
                    alias = al;
                    break;
                }
            }
            AsymmetricKeyEntry pk = store.GetKey(alias);

            foreach (X509CertificateEntry c in store.GetCertificateChain(alias))
            {
                chain.Add(c.Certificate);
            }
            RsaPrivateCrtKeyParameters parameters = pk.Key as RsaPrivateCrtKeyParameters;

            PdfReader  reader  = new PdfReader(src);
            FileStream os      = new FileStream(dest, FileMode.Create);
            PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0', null, true);
            // Creating the appearance
            PdfSignatureAppearance appearance = stamper.SignatureAppearance;

            appearance.SetVisibleSignature(name);
            appearance.CertificationLevel = PdfSignatureAppearance.CERTIFIED_FORM_FILLING;
            // Creating the signature
            IExternalSignature pks = new PrivateKeySignature(parameters, "SHA-256");

            MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, CryptoStandard.CMS);
        }
예제 #23
0
        public void Sign(String src, String dest, ICollection <X509Certificate> chain, Session session, String alias,
                         String digestAlgorithm, CryptoStandard subfilter, String reason, String location,
                         ICollection <ICrlClient> crlList, IOcspClient ocspClient, ITSAClient tsaClient, int estimatedSize)
        {
            // Creating the reader and the stamper
            PdfReader  reader  = null;
            PdfStamper stamper = null;
            FileStream os      = null;

            try {
                reader  = new PdfReader(src);
                os      = new FileStream(dest, FileMode.Create);
                stamper = PdfStamper.CreateSignature(reader, os, '\0');
                // Creating the appearance
                PdfSignatureAppearance appearance = stamper.SignatureAppearance;
                appearance.Reason   = reason;
                appearance.Location = location;
                appearance.SetVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig");
                // Creating the signature
                IExternalSignature pks = new CryptokiPrivateKeySignature(session, alias);
                MakeSignature.SignDetached(appearance, pks, chain, crlList, ocspClient, tsaClient, estimatedSize, subfilter);
            } finally {
                if (reader != null)
                {
                    reader.Close();
                }
                if (stamper != null)
                {
                    stamper.Close();
                }
                if (os != null)
                {
                    os.Close();
                }
            }
        }
        public void Sign(String src, String name, String dest, X509Certificate[] chain, ICipherParameters pk,
                         String digestAlgorithm, PdfSigner.CryptoStandard subfilter, String reason, String location,
                         String contact, String fullName)
        {
            PdfReader reader = new PdfReader(src);
            PdfSigner signer = new PdfSigner(reader, new FileStream(dest, FileMode.Create), new StampingProperties());

            // Create the signature appearance
            PdfSignatureAppearance appearance = signer.GetSignatureAppearance();

            appearance.SetReason(reason);
            appearance.SetLocation(location);
            appearance.SetContact(contact);

            signer.SetFieldName(name);

            // Set the signature event to allow modification of the signature dictionary.
            signer.SetSignatureEvent(new CustomISignatureEvent(fullName));

            PrivateKeySignature pks = new PrivateKeySignature(pk, digestAlgorithm);

            // Sign the document using the detached mode, CMS or CAdES equivalent.
            signer.SignDetached(pks, chain, null, null, null, 0, subfilter);
        }
예제 #25
0
        private void CreateNewSignatureField(SignInformation signInfo)
        {
            try
            {
                pdfStamper             = PdfStamper.CreateSignature(document, stream, '\0', null, true);
                sap                    = pdfStamper.SignatureAppearance;
                sap.Reason             = signInfo.reason;
                sap.Location           = signInfo.location;
                sap.CertificationLevel = signInfo.certifyLevel;

                PdfSignature sig = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
                sig.Reason           = signInfo.reason;
                sap.CryptoDictionary = sig;

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

                sap.PreClose(exc);
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
예제 #26
0
        public void EmptySignature(String src, String dest, String fieldname, X509Certificate[] chain)
        {
            PdfReader reader = new PdfReader(src);
            PdfSigner signer = new PdfSigner(reader, new FileStream(dest, FileMode.Create), new StampingProperties());

            PdfSignatureAppearance appearance = signer.GetSignatureAppearance();

            appearance
            .SetPageRect(new Rectangle(36, 748, 200, 100))
            .SetPageNumber(1)
            .SetCertificate(chain[0]);
            signer.SetFieldName(fieldname);

            /* ExternalBlankSignatureContainer constructor will create the PdfDictionary for the signature
             * information and will insert the /Filter and /SubFilter values into this dictionary.
             * It will leave just a blank placeholder for the signature that is to be inserted later.
             */
            IExternalSignatureContainer external = new ExternalBlankSignatureContainer(PdfName.Adobe_PPKLite,
                                                                                       PdfName.Adbe_pkcs7_detached);

            // Sign the document using an external container
            // 8192 is the size of the empty signature placeholder.
            signer.SignExternalContainer(external, 8192);
        }
예제 #27
0
        public void Sign(string SigReason, string SigContact, string SigLocation, bool visible)
        {
            PdfReader reader = new PdfReader(this.inputPDF);
            //Activate MultiSignatures
            PdfStamper st = PdfStamper.CreateSignature(reader, new FileStream(this.outputPDF, FileMode.Create, FileAccess.Write), '\0', null, true);

            //To disable Multi signatures uncomment this line : every new signature will invalidate older ones !
            //PdfStamper st = PdfStamper.CreateSignature(reader, new FileStream(this.outputPDF, FileMode.Create, FileAccess.Write), '\0');

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

            sap.SetCrypto(this.myCert.Akp, this.myCert.Chain, null, PdfSignatureAppearance.WINCER_SIGNED);
            sap.Reason   = SigReason;
            sap.Contact  = SigContact;
            sap.Location = SigLocation;
            if (visible)
            {
                sap.SetVisibleSignature(new iTextSharp.text.Rectangle(100, 100, 250, 150), 1, null);
            }

            st.Close();
        }
예제 #28
0
        public static void signPdfFile(string sourceDocument, string destinationPath, Stream privateKeyStream, string keyPassword, string reason, string location)
        {
            Pkcs12Store pk12 = new Pkcs12Store(privateKeyStream, keyPassword.ToCharArray());

            privateKeyStream.Dispose();

            //then Iterate throught certificate entries to find the private key entry
            string alias = null;

            foreach (string tAlias in pk12.Aliases)
            {
                if (pk12.IsKeyEntry(tAlias))
                {
                    alias = tAlias;
                    break;
                }
            }
            var pk    = pk12.GetKey(alias).Key;
            var ce    = pk12.GetCertificateChain(alias);
            var chain = new X509Certificate[ce.Length];

            for (int k = 0; k < ce.Length; ++k)
            {
                chain[k] = ce[k].Certificate;
            }
            // reader and stamper
            PdfReader          reader     = new PdfReader(sourceDocument);
            FileStream         fout       = new FileStream(destinationPath, FileMode.Create, FileAccess.ReadWrite);
            StampingProperties properties = new StampingProperties();
            PdfSigner          signer     = new PdfSigner(reader, fout, properties);

            PdfSignatureAppearance appearance = signer.GetSignatureAppearance().SetReason(reason).SetLocation(location);
            IExternalSignature     pks        = new PrivateKeySignature(pk, "SHA-512");

            signer.SignDetached(pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CMS);
        }
    public void Sign(String src, String dest,
                     ICollection <X509Certificate> chain, X509Certificate2 pk,
                     String digestAlgorithm, CryptoStandard subfilter,
                     String reason, String location,
                     ICollection <ICrlClient> crlList,
                     IOcspClient ocspClient,
                     ITSAClient tsaClient,
                     int estimatedSize, int RowIdx, int RowHeight, int x, int y, int NameWidth, int DateWidth,
                     String RevIndex, String RevStep, String Reason, String Name, String Date)
    {
        // Creating the reader and the stamper
        PdfReader  reader  = null;
        PdfStamper stamper = null;
        FileStream os      = null;

        try
        {
            reader = new PdfReader(src);
            os     = new FileStream(dest, FileMode.Create);
            // os = new FileStream(dest, FileMode.Create, FileAccess.Write);
            //Activate MultiSignatures
            stamper = PdfStamper.CreateSignature(reader, os, '\0', null, true);
            //To disable Multi signatures uncomment this line : every new signature will invalidate older ones !
            //stamper = PdfStamper.CreateSignature(reader, os, '\0');
            // Creating the appearance
            PdfSignatureAppearance appearance = stamper.SignatureAppearance;
            Rectangle rectangle = new Rectangle(x, y + RowIdx * RowHeight, x + NameWidth + DateWidth, y + (RowIdx + 1) * RowHeight);
            appearance.SetVisibleSignature(rectangle, 1, "Revision " + RevIndex + "|" + RevStep);
            appearance.Reason                 = "marked as changed";
            appearance.Location               = location;
            appearance.Layer2Text             = "Signed on " + DateTime.Now;
            appearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION;
            PdfTemplate n2   = appearance.GetLayer(2);
            Font        font = new Font();
            font.SetColor(255, 0, 0);
            font.Size = 10;
            ColumnText ct1 = new ColumnText(n2);
            ct1.SetSimpleColumn(new Phrase(Name, font), 0, 0, NameWidth, rectangle.Height, 15, Element.ALIGN_LEFT);
            ct1.Go();
            ColumnText ct2 = new ColumnText(n2);
            ct2.SetSimpleColumn(new Phrase(Date, font), NameWidth, 0, rectangle.Width, rectangle.Height, 15, Element.ALIGN_LEFT);
            ct2.Go();
            //n2.ConcatCTM(1, 0, 0, -1, 0, 0);
            //n2.SaveState();
            // Creating the signature
            IExternalSignature pks = new X509Certificate2Signature(pk, digestAlgorithm);
            MakeSignature.SignDetached(appearance, pks, chain, crlList, ocspClient, tsaClient, estimatedSize, subfilter);
        }
        catch (Exception ex)
        {
            Console.WriteLine("GMA: " + ex.Message);
        }
        finally
        {
            if (reader != null)
            {
                reader.Close();
            }
            if (stamper != null)
            {
                stamper.Close();
            }
            if (os != null)
            {
                os.Close();
            }
        }
    }
예제 #30
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();
        }
예제 #31
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);



            /////////////////////////////////////////////////////////////////////////////
        }
예제 #32
0
        public byte[] signPdfWithSmartCard(string terminal, ECertificate signatureCertificate, string pinCode, string pdfFileName)
        {
            byte[]     buffer  = null;
            PdfReader  reader  = null;
            PdfStamper stamper = null;
            FileStream os      = null;

            try
            {
                string dest = AppDomain.CurrentDomain.BaseDirectory + "\\tmp.pdf";
                if (File.Exists(dest))
                {
                    File.Delete(dest);
                }
                IExternalSignature pks = new SmartCardPrivateKeySignature(terminal, pinCode, signatureCertificate);
                reader  = new PdfReader(pdfFileName);
                os      = new FileStream(dest, FileMode.Create);
                stamper = PdfStamper.CreateSignature(reader, os, '\0');

                Org.BouncyCastle.Asn1.Esf.SignaturePolicyIdentifier policy = new Org.BouncyCastle.Asn1.Esf.SignaturePolicyIdentifier();
                DateTime dtNow = DateTime.Now;
                PdfSignatureAppearance appearance = stamper.SignatureAppearance;
                appearance.Reason   = "";
                appearance.Location = "";
                appearance.SignDate = dtNow;
                PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKMS, PdfName.ADBE_PKCS7_SHA1);
                dic.Date = new PdfDate(dtNow);
                appearance.CryptoDictionary = dic;
                ICollection <Org.BouncyCastle.X509.X509Certificate> chain = new List <Org.BouncyCastle.X509.X509Certificate>();


                X509Certificate2 cert = signatureCertificate.asX509Certificate2();

                X509Chain x509chain = new X509Chain();
                x509chain.Build(cert);
                foreach (X509ChainElement x509ChainElement in x509chain.ChainElements)
                {
                    chain.Add(DotNetUtilities.FromX509Certificate(x509ChainElement.Certificate));
                }


                MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, CryptoStandard.CADES, policy);
                buffer = File.ReadAllBytes(dest);
                File.Delete(dest);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (stamper != null)
                {
                    stamper.Close();
                }
                if (os != null)
                {
                    os.Close();
                }
            }
            return(buffer);
        }
        /**
         * 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);
        }
예제 #34
0
파일: PDFSigner.cs 프로젝트: tixsys/esteid
        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);
        }