Esempio n. 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);
        }
Esempio n. 2
0
        public void Sign(String src, String dest, X509Certificate[] chain, ICipherParameters pk,
                         String digestAlgorithm, PdfSigner.CryptoStandard subfilter, String reason, String location,
                         ICollection <ICrlClient> crlList, IOcspClient ocspClient, ITSAClient tsaClient, int estimatedSize)
        {
            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)

            // Specify if the appearance before field is signed will be used
            // as a background for the signed field. The "false" value is the default value.
            .SetReuseAppearance(false)
            .SetPageRect(rect)
            .SetPageNumber(1);
            signer.SetFieldName("sig");

            IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm);

            // Sign the document using the detached mode, CMS or CAdES equivalent.
            signer.SignDetached(pks, chain, crlList, ocspClient, tsaClient, estimatedSize, subfilter);
        }
Esempio n. 3
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);
            }
        }
        public void Sign2(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);

            // Creating the appearance for layer 2
            PdfFormXObject n2 = appearance.GetLayer2();

            // Custom text, custom font, and right-to-left writing
            // Characters: لورانس العرب
            Text text = new Text("\u0644\u0648\u0631\u0627\u0646\u0633 \u0627\u0644\u0639\u0631\u0628");

            text.SetFont(PdfFontFactory.CreateFont("../../../resources/font/NotoNaskhArabic-Regular.ttf",
                                                   PdfEncodings.IDENTITY_H, true));
            text.SetBaseDirection(BaseDirection.RIGHT_TO_LEFT);
            new Canvas(n2, signer.GetDocument()).Add(new Paragraph(text).SetTextAlignment(TextAlignment.RIGHT));

            IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm);

            signer.SignDetached(pks, chain, null, null, null, 0, subfilter);
        }
Esempio n. 5
0
        public void Sign(String src, String dest, X509Certificate[] chain, ICipherParameters pk,
                         String digestAlgorithm, PdfSigner.CryptoStandard subfilter,
                         int certificationLevel, 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
            PdfSignatureAppearance appearance = signer.GetSignatureAppearance();

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

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

            appearance.SetPageRect(rect).SetPageNumber(1);
            signer.SetFieldName("sig");

            /* Set the document's certification level. This parameter defines if changes are allowed
             * after the applying of the signature.
             */
            signer.SetCertificationLevel(certificationLevel);

            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);
        }
        public void Sign1(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());

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

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

            // This name corresponds to the name of the field that already exists in the document.
            signer.SetFieldName(name);

            // Set the custom text and a custom font
            appearance.SetLayer2Text("This document was signed by Bruno Specimen");
            appearance.SetLayer2Font(PdfFontFactory.CreateFont(StandardFonts.TIMES_ROMAN));

            IExternalSignature 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);
        }
        public void Sign(String src, String name, String dest, X509Certificate[] chain,
                         ICipherParameters pk, String digestAlgorithm, PdfSigner.CryptoStandard subfilter,
                         String reason, String location, PdfSignatureAppearance.RenderingMode renderingMode, ImageData image)
        {
            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);

            // This name corresponds to the name of the field that already exists in the document.
            signer.SetFieldName(name);

            appearance.SetLayer2Text("Signed on " + DateTime.Now);

            // Set the rendering mode for this signature.
            appearance.SetRenderingMode(renderingMode);

            // Set the Image object to render when the rendering mode is set to RenderingMode.GRAPHIC
            // or RenderingMode.GRAPHIC_AND_DESCRIPTION.
            appearance.SetSignatureGraphic(image);

            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);
        }
Esempio n. 8
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);
        }
Esempio n. 9
0
        public void SignAgain(String src, 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().UseAppendMode());

            PdfSignatureAppearance appearance = signer.GetSignatureAppearance();

            appearance.SetReason(reason);
            appearance.SetLocation(location);
            appearance.SetReuseAppearance(false);
            Rectangle rect = new Rectangle(36, 700, 200, 100);

            appearance.SetPageRect(rect).SetPageNumber(1);
            signer.SetFieldName("Signature2");

            PrivateKeySignature pks = new PrivateKeySignature(pk, digestAlgorithm);

            signer.SignDetached(pks, chain, null, null, null, 0, subfilter);
        }
Esempio n. 10
0
        public void Sign(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());

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

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

            // This name corresponds to the name of the field that already exists in the document.
            signer.SetFieldName(name);

            // Get the background layer and draw a gray rectangle as a background.
            PdfFormXObject n0     = appearance.GetLayer0();
            float          x      = n0.GetBBox().ToRectangle().GetLeft();
            float          y      = n0.GetBBox().ToRectangle().GetBottom();
            float          width  = n0.GetBBox().ToRectangle().GetWidth();
            float          height = n0.GetBBox().ToRectangle().GetHeight();
            PdfCanvas      canvas = new PdfCanvas(n0, signer.GetDocument());

            canvas.SetFillColor(ColorConstants.LIGHT_GRAY);
            canvas.Rectangle(x, y, width, height);
            canvas.Fill();

            // Set the signature information on layer 2
            PdfFormXObject n2 = appearance.GetLayer2();
            Paragraph      p  = new Paragraph("This document was signed by Bruno Specimen.");

            new Canvas(n2, signer.GetDocument()).Add(p);

            IExternalSignature 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);
        }
Esempio n. 11
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);
        }
        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);
        }
        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);
        }
        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);
        }
Esempio n. 15
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);
        }