示例#1
0
        public static void Sign(string fileName, string signedFileName, string reason, string location,
                                string privateKeyFileName, string certFileName, string password)
        {
            PdfReader reader = new PdfReader(fileName);
            PdfWriter write  = new PdfWriter(signedFileName);
            PdfSigner signer = new PdfSigner(reader, write, false);

            PdfSignatureAppearance appearance = signer.GetSignatureAppearance();

            appearance.SetReason(reason);
            appearance.SetLocation(location);
            appearance.SetReuseAppearance(false);

            Rectangle rect = new Rectangle(36, 648, 200, 100);

            appearance.SetPageRect(rect);
            appearance.SetPageNumber(1);

            signer.SetFieldName("sig");

            IExternalSignature pks = new PrivateKeySignature(ReadPrivateKey(privateKeyFileName, password), GetEncryptionAlgorithm());

            X509CertificateParser parser = new X509CertificateParser();
            X509Certificate       cert   = LoadCertificate(certFileName);

            X509Certificate[] chain = new X509Certificate[1];
            chain[0] = cert;
            PdfSigner.CryptoStandard subfilter = GetSubFilter();

            signer.SignDetached(pks, chain, null, null, null, 0, subfilter);
        }
示例#2
0
        private void BuildSignatureAppearance(PdfSigner signer, Signature signing)
        {
            // Creating the appearance
            PdfSignatureAppearance appearance = signer.GetSignatureAppearance();

            appearance.SetReason(signing.SignReason);
            appearance.SetContact(signing.SignContact);
            appearance.SetLocation(signing.SignLocation);

            var arial = PdfFontFactory.CreateFont(Environment.GetEnvironmentVariable("WINDIR") + "\\Fonts\\Arial.ttf", PdfName.WinAnsiEncoding.GetValue(), true);

            appearance.SetLayer2Font(arial);
            if (!signing.AllowMultiSigning)
            {
                signer.SetCertificationLevel(PdfSigner.CERTIFIED_FORM_FILLING_AND_ANNOTATIONS);
                appearance.SetCertificate(signer.GetSignatureAppearance().GetCertificate());
            }

            if (signing.DisplaySignatureInDocument)
            {
                var signPage = SignPageNr(signer, signing);
                var left     = signing.LeftX;
                var bottom   = signing.LeftY;
                var width    = signing.RightX - left;
                var height   = signing.RightY - bottom;

                var rect = new Rectangle(left, bottom, width, height);
                appearance.SetPageRect(rect);
                appearance.SetPageNumber(signPage);
            }
        }
示例#3
0
        public static void Sign(string input, string output, ImageData stamper, ICipherParameters privateKey, X509Certificate[] chain, string flag)
        {
            PdfDocument document = new PdfDocument(new PdfReader(input));

            PdfAcroForm acroForm = PdfAcroForm.GetAcroForm(document, false);
            bool        append   = (acroForm != null && acroForm.GetSignatureFlags() != 0);

            int pageNumber = document.GetNumberOfPages();

            RegexBasedLocationExtractionStrategy strategy = new RegexBasedLocationExtractionStrategy(flag);
            PdfDocumentContentParser             parser   = new PdfDocumentContentParser(document);

            parser.ProcessContent(pageNumber, strategy);
            var locations = new List <IPdfTextLocation>(strategy.GetResultantLocations());

            document.Close();

            StampingProperties properties = new StampingProperties();

            properties = append ? properties.UseAppendMode() : properties;

            PdfSigner signer = new PdfSigner(new PdfReader(input), new FileStream(output, FileMode.Create), properties);

            signer.SetCertificationLevel(PdfSigner.CERTIFIED_NO_CHANGES_ALLOWED);

            PdfSignatureAppearance appearance = signer.GetSignatureAppearance();

            appearance.SetPageNumber(pageNumber);

            int size = locations.Count;

            if (size != 0)
            {
                IPdfTextLocation location = locations[size - 1];

                float flagX = location.GetRectangle().GetX();
                float flagY = location.GetRectangle().GetY();

                float width  = stamper.GetWidth();
                float height = stamper.GetHeight();

                float x = flagX - width / 2;
                float y = flagY - height / 2;

                appearance.SetRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC);
                appearance.SetSignatureGraphic(stamper);
                appearance.SetPageRect(new Rectangle(x, y, width, height));
            }

            PrivateKeySignature signature = new PrivateKeySignature(privateKey, DigestAlgorithms.SHA256);

            signer.SignDetached(signature, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES);
        }
示例#4
0
        private static void ConfiguraAparencia(PdfSigner objStamper, CertSimples cert, int X, int Y, int Largura, int Altura, int Pagina, int Rotation, string Contact = "", string Reason = "Assinatura Digital", string Location = "Indústrias Nucleares do Brasil S/A - INB", string Creator = "Assinador da INB", TipoAssinatura Tipo = TipoAssinatura.Normal, string Cargo = "", string CREACRM = "")
        {
            PdfDocument pdfDoc = objStamper.GetDocument();
            PdfPage     oPage = pdfDoc.GetPage(Pagina);
            int         LarguraAssinatura = Largura;
            int         AlturaAssinatura = Altura;
            int         X_Ajustado, Y_Ajustado;

            X_Ajustado = X;
            Y_Ajustado = Y;
            var    crop = oPage.GetCropBox();
            float  Left, Top, Width, Height;
            Bitmap bmp            = Graphic.ConfiguraBMP(cert, out Altura, Tipo);

            if (Rotation == 270)
            {
                Left = (int)crop.GetLeft() + X_Ajustado;
                Top  = (int)crop.GetRight() - (Y_Ajustado + AlturaAssinatura + 5);
            }
            else if (Rotation == 90)
            {
                Left = (int)crop.GetRight() + X_Ajustado;
                Top  = (int)crop.GetLeft() - (Y_Ajustado + AlturaAssinatura + 5);
            }
            else
            {
                Left = (int)crop.GetLeft() + X_Ajustado;
                Top  = (int)crop.GetTop() - (Y_Ajustado + AlturaAssinatura + 5);
            }
            Width  = LarguraAssinatura;
            Height = AlturaAssinatura;
            iText.Kernel.Geom.Rectangle oRetangulo = new iText.Kernel.Geom.Rectangle(Left, Top, Width, Height);
            var pageSize          = pdfDoc.GetPage(Pagina).GetMediaBox();
            var signaturePosition = new iText.Kernel.Geom.Rectangle(pageSize.GetLeft(), pageSize.GetBottom(), pageSize.GetWidth(), pageSize.GetHeight());
            PdfSignatureAppearance signatureAppearance = objStamper.GetSignatureAppearance();
            var memoryStream = new MemoryStream();

            bmp.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            iText.IO.Image.ImageData pic = iText.IO.Image.ImageDataFactory.Create(memoryStream.ToArray());
            signatureAppearance.SetReason(Reason);
            signatureAppearance.SetLocation(Location);
            signatureAppearance.SetSignatureCreator(Creator);
            signatureAppearance.SetSignatureGraphic(pic);
            signatureAppearance.SetRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC);
            signatureAppearance.SetPageRect(oRetangulo);
            signatureAppearance.SetPageNumber(Pagina);
        }
示例#5
0
        public static byte[] EmptySignature()
        {
            byte[] Hash = null;

            PdfReader reader = new PdfReader(src);

            using (FileStream fout = new FileStream(temp, FileMode.Create))
            {
                StampingProperties sp = new StampingProperties();
                sp.UseAppendMode();

                PdfSigner pdfSigner = new PdfSigner(reader, fout, sp);
                pdfSigner.SetFieldName("Signature");

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

                SHA256 sha           = new SHA256CryptoServiceProvider();
                String hashAlgorithm = DigestAlgorithms.SHA256;

                var externalSignature = new ExternalHashingSignatureContainer(PdfName.Adobe_PPKLite,
                                                                              PdfName.Adbe_pkcs7_detached);
                pdfSigner.SignExternalContainer(externalSignature, 8192);
                digest = externalSignature.Hash;

                var base64digest = Convert.ToBase64String(digest);
            }

            PdfReader  readerFout       = new PdfReader(temp);
            FileStream destPdf          = new FileStream(dest, FileMode.Create);
            PdfSigner  pdfSigner2       = new PdfSigner(readerFout, destPdf, new StampingProperties());
            var        hashBase65       = Convert.ToBase64String(digest);
            string     signedBase64Hash = String.Empty;

            byte[] signedHash = ConvertToBytes(signedBase64Hash);
            var    container  = new MyExternalSignatureContainer(signedHash, GetChains(), Hash);

            pdfSigner2.SignExternalContainer(container, 8192);

            return(Hash);
        }
示例#6
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);
        }
示例#7
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));
                }
            }
        }
        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);
                }
            }
        }
示例#9
0
        public byte[] GenerirajPotpisaniDokument(byte[] document, string documentName, string signingReason, string signingLocation)
        {
            try
            {
                string alias = "";
                List <Org.BouncyCastle.X509.X509Certificate> chain = new List <Org.BouncyCastle.X509.X509Certificate>();

                var location = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AppDomain.CurrentDomain.RelativeSearchPath ?? "");
                //var destinationPath = $@"Data\{documentName}";
                //destinationPath = Path.Combine(location, destinationPath);
                var destinationPath = iConfig["DocumentDestinationPath"] + documentName;


                var certPath = @"C:\Users\Crega\Source\Repos\PdfSigner\PdfSigner\bin\Debug\netcoreapp3.0\certifikat.pfx";
                certPath = Path.Combine(location, certPath);
                var    cert       = File.ReadAllBytes(certPath);
                Stream certStream = new MemoryStream(cert);

                Pkcs12Store store = new Pkcs12Store(certStream, "12345".ToCharArray());

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

                Stream                     documentStream = new MemoryStream(document);
                PdfReader                  reader         = new PdfReader(documentStream);
                FileStream                 os             = new FileStream(destinationPath, FileMode.Create);
                StampingProperties         sp             = new StampingProperties();
                iText.Signatures.PdfSigner signer         = new iText.Signatures.PdfSigner(reader, os, sp);
                PdfSignatureAppearance     appearance     = signer.GetSignatureAppearance();
                appearance.SetReason(signingReason);
                appearance.SetLocation(signingLocation);
                appearance.SetContact("*****@*****.**");
                //appearance.SetPageRect(new iText.Kernel.Geom.Rectangle(36, 748, 144, 780));
                appearance.SetPageNumber(1);
                appearance.SetCertificate(chain[0]);

                // Creating the signature
                IExternalSignature pks = new PrivateKeySignature(parameters, DigestAlgorithms.SHA256);
                signer.SignDetached(pks, chain.ToArray(), null, null, null, 0, iText.Signatures.PdfSigner.CryptoStandard.CADES);
                //MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES);
                os.Close();
                certStream.Close();
                var documentToReturn = File.ReadAllBytes(destinationPath);
                File.Delete(destinationPath);
                return(documentToReturn);
            }
            catch (Exception ex)
            {
            }
            return(null);
        }