Пример #1
0
 private void SignOpenOfficeXML(Package package)
 {
     try
     {
         Licensing.ShowDemoMessage();
         DigitalCertificate.LogOnEToken(this.DigitalSignatureCertificate);
         if (package == null)
         {
             throw new ArgumentNullException();
         }
         List <Uri> uris = new List <Uri>();
         List <PackageRelationshipSelector> packageRelationshipSelectors = new List <PackageRelationshipSelector>();
         foreach (PackageRelationship relationshipsByType in package.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"))
         {
             this.CreateListOfSignableItems(relationshipsByType, uris, packageRelationshipSelectors);
         }
         PackageDigitalSignatureManager packageDigitalSignatureManager = new PackageDigitalSignatureManager(package)
         {
             CertificateOption = CertificateEmbeddingOption.InSignaturePart
         };
         packageDigitalSignatureManager.Sign(uris, this.DigitalSignatureCertificate, packageRelationshipSelectors);
     }
     catch
     {
         throw;
     }
 }
Пример #2
0
        /// <summary>
        /// Publishes a generic letter on School letterhead.  PDF protection options are set via the boolean properties of this object.
        /// Document is digitally signed using a certificate generated by the local certificate authority in the dublinschool.org domain.
        /// </summary>
        /// <param name="bodyHtml">Body of the letter.</param>
        /// <param name="signerId">Employee id of the Faculty who will put their signature on the document.  (automatically adds the signature image to the end of the document.</param>
        public Document PublishGenericLetter(String bodyHtml, bool digitallySign = false, int signerId = -1)
        {
            String   html     = Template.Replace("{content}", bodyHtml).Replace("{signature}", signerId == -1? "" : SignatureImage(signerId));
            Document document = PdfConverter.ConvertHtmlToPdfDocumentObject(html, BaseURL, BaseURL);

            if (digitallySign)
            {
                try
                {
                    /// digitally sign the document.
                    HtmlElementMapping dsMap = PdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByMappingId("digital_signature_element");
                    if (dsMap != null)
                    {
                        PdfPage    page      = dsMap.PdfRectangles.Last().PdfPage;
                        RectangleF rectangle = dsMap.PdfRectangles.Last().Rectangle;

                        DigitalCertificate cert = DocumentSigningCertificate;

                        DigitalSignatureElement dse = new DigitalSignatureElement(rectangle, cert);
                        dse.Reason      = "Ensure Document Integrity and Protect from unwanted changes.";
                        dse.ContactInfo = "Contact Email:  [email protected]";
                        dse.Location    = "Issuing Web Server";
                        page.AddElement(dse);
                    }
                }
                catch (Exception e)
                {
                    WebhostEventLog.CommentLog.LogError("Failed to Apply digital signature to document...{0}{1}", Environment.NewLine, e.Message);
                }
            }
            return(document);
        }
Пример #3
0
 private void SignXml(string inputFile, string outputFile)
 {
     try
     {
         Licensing.ShowDemoMessage();
         DigitalCertificate.LogOnEToken(this.DigitalSignatureCertificate);
         XmlDocument xmlDocument = new XmlDocument()
         {
             PreserveWhitespace = this.RemoveWhitespaces
         };
         xmlDocument.Load(inputFile);
         SignedXml signedXml = new SignedXml(xmlDocument);
         RSACryptoServiceProvider rSACryptoServiceProvider = null;
         try
         {
             string xmlString = this.DigitalSignatureCertificate.PrivateKey.ToXmlString(true);
             rSACryptoServiceProvider = new RSACryptoServiceProvider(new CspParameters(24))
             {
                 PersistKeyInCsp = false
             };
             rSACryptoServiceProvider.FromXmlString(xmlString);
             signedXml.SigningKey = rSACryptoServiceProvider;
         }
         catch
         {
             rSACryptoServiceProvider = this.DigitalSignatureCertificate.PrivateKey as RSACryptoServiceProvider;
             signedXml.SigningKey     = rSACryptoServiceProvider;
         }
         signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
         if (this.IncludeKeyInfo || this.IncludeSignatureCertificate)
         {
             KeyInfo keyInfos = new KeyInfo();
             if (this.IncludeKeyInfo)
             {
                 keyInfos.AddClause(new RSAKeyValue(rSACryptoServiceProvider));
             }
             if (this.IncludeSignatureCertificate)
             {
                 keyInfos.AddClause(new KeyInfoX509Data(this.DigitalSignatureCertificate.GetRawCertData()));
             }
             signedXml.KeyInfo = keyInfos;
         }
         Reference reference = new Reference();
         reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
         reference.AddTransform(new XmlDsigExcC14NTransform());
         reference.Uri          = "";
         reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";
         signedXml.AddReference(reference);
         signedXml.ComputeSignature();
         SignatureDescription signatureDescription = new SignatureDescription();
         XmlElement           xml = signedXml.GetXml();
         xmlDocument.DocumentElement.AppendChild(xmlDocument.ImportNode(xml, true));
         xmlDocument.Save(outputFile);
     }
     catch
     {
         throw;
     }
 }
        public ActionResult CreatePdf(IFormCollection collection)
        {
            // Create a PDF document
            Document pdfDocument = new Document();

            // Set license key received after purchase to use the converter in licensed mode
            // Leave it not set to use the converter in demo mode
            pdfDocument.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c=";

            // Add a page to PDF document
            PdfPage pdfPage = pdfDocument.AddPage();

            try
            {
                string htmlWithDigitalSignatureMarker = collection["htmlStringTextBox"];
                string baseUrl = collection["baseUrlTextBox"];

                // Add a HTML string with a marker for digital signature to PDF document
                HtmlToPdfElement htmlToPdfElement = new HtmlToPdfElement(htmlWithDigitalSignatureMarker, baseUrl);
                pdfPage.AddElement(htmlToPdfElement);

                // Make the HTML element with 'digital_signature_element' mapping ID a link to digital signature properties
                HtmlElementMapping digitalSignatureMapping = htmlToPdfElement.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByMappingId("digital_signature_element");
                if (digitalSignatureMapping != null)
                {
                    PdfPage    digitalSignaturePage      = digitalSignatureMapping.PdfRectangles[0].PdfPage;
                    RectangleF digitalSignatureRectangle = digitalSignatureMapping.PdfRectangles[0].Rectangle;

                    string certificateFilePath = m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/Certificates/evopdf.pfx";

                    // Get the certificate from password protected PFX file
                    DigitalCertificatesCollection certificates = DigitalCertificatesStore.GetCertificates(certificateFilePath, "evopdf");
                    DigitalCertificate            certificate  = certificates[0];

                    // Create the digital signature
                    DigitalSignatureElement signature = new DigitalSignatureElement(digitalSignatureRectangle, certificate);
                    signature.Reason      = "Protect the document from unwanted changes";
                    signature.ContactInfo = "The contact email is [email protected]";
                    signature.Location    = "Development server";
                    digitalSignaturePage.AddElement(signature);
                }

                // Save the PDF document in a memory buffer
                byte[] outPdfBuffer = pdfDocument.Save();

                // Send the PDF file to browser
                FileResult fileResult = new FileContentResult(outPdfBuffer, "application/pdf");
                fileResult.FileDownloadName = "Digital_Signatures.pdf";

                return(fileResult);
            }
            finally
            {
                // Close the PDF document
                pdfDocument.Close();
            }
        }
Пример #5
0
        protected override void Seed(SurityTrial.Context.SurityDBContext context)
        {
            var privateKeyBase64 = "MIILHAIBAzCCCtgGCSqGSIb3DQEHAaCCCskEggrFMIIKwTCCBhoGCSqGSIb3DQEHAaCCBgsEggYHMIIGAzCCBf8GCyqGSIb3DQEMCgECoIIE/jCCBPowHAYKKoZIhvcNAQwBAzAOBAjbyHCFNrQjIAICB9AEggTY315GG6aK1EtypvnLc+HsjG+e0Dzbms+m3a00ECu38TiwU7EWRfP6R6Aho4SMBJdQWIQe0inz0nhk1xp0flc5BSGzJwjwCAQa9eqDC5puZxEDk0V1cTnfx3XdB7W9x1hTpNE5SpMS3QbHWZqQNwWaufTRkoG5BDx7r6DXi65aQx3hn0KvpF6EUflGnp9vWcKEu3X9CHL0g2HtLpubkvjr0LCOahKgT7FI1DPa2nRdazEsRTYMntru6JZIVYTYMpdYCL/d3/Tk9mgtDWx7IfRGY0jl3LHX+eh17EIbyhnaPLvSV2YHdPVb+FXwsREEJZ//I241CviRS9dh0vGKjkDs5i8e+8VFnMJraAq7LlqLYyKDoymaXEGt04o7hkq0O6EhvV0pRP+FMxOv1mP6LZUEaVa9e3dtYY04LJJVnLyzybdqi2QHPnPqCSE97G2r/kLFDwx3UGiJgyI9kMXThY1V7wcFmeptk5PWc9sFsXzb6zVq0wbdjzYK6a7U8+2UdJ7T/5wM/ecLz1vSsy9SqkuzjkL+bqs4+hBnlZ/prkw3B/RVHk8oCUOtpoUQJuXlzRVeAeVH5NVlxfLvjZRq+KzwSuJQ9oqGtSVAj/TketTgOw8SammADp7SP2OJMgq4SwQBz149eo9VDWLmdzJ8kEvzwpOxQDgGZ27x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pREgkvQ3GJh7KIb632KPPO9Zbiumfw6uDelnSb7dg3bYw8Woq8Jxx2gpC5n8gcQR1qcM1Rjo7BAAgeQWljBuGIE5t4IM1hg6ZlV5Eav9kxvMX5e8i7efHXEi91i200N+oOHg761W2djbpJGcuFVh4M6DiIv8gyMDPPel4S+8ad9LtsrIXQb5jJ24f8+CJEPzPzEEwWAup0PovXOIOmTukX+L2937ff17bMDswHzAHBgUrDgMCGgQUHJZvfvefEv6UxdJ4wTGoWoOz/5MEFOby3IqtoMwl5ab/hWJPn3DFKJLRAgIH0A==";

            var digitalCertificate = new DigitalCertificate();

            digitalCertificate.PrivateKey = Convert.FromBase64String(privateKeyBase64);
            digitalCertificate.PublicKey  = Convert.FromBase64String(publicKeyBase64);

            context.DigitalCertificate.AddOrUpdate(digitalCertificate);
            context.SaveChanges();
        }
Пример #6
0
        private void Form1_Load(object sender, EventArgs e)
        {
            var store = new Store();
            var cd    = new DigitalCertificate {
                FriendlyName = "Sem assinatura digital"
            };

            listaCertificados = new List <DigitalCertificate>();
            listaCertificados.Add(cd);

            listaCertificados.AddRange(store.GetListCertificates(CertSignStoreName.My, CertSignStoreLocation.CurrentUser));
            cbxCertificados.DataSource     = listaCertificados;
            cbxCertificados.SelectionStart = 1;
        }
Пример #7
0
        public DigitalCertificate GetCertificate(string name)
        {
            var list = GetListCertificates(CertSignStoreName.Root, CertSignStoreLocation.CurrentUser);
            DigitalCertificate cert = null;

            for (var i = 0; i < list.Count; i++)
            {
                var c = list[i];
                if (c.Name == name)
                {
                    cert = c;
                }
            }
            return(cert);
        }
Пример #8
0
 private void SignXPSStream(Stream inputStream)
 {
     try
     {
         Licensing.ShowDemoMessage();
         DigitalCertificate.LogOnEToken(this.DigitalSignatureCertificate);
         using (Package package = Package.Open(inputStream, FileMode.Open, FileAccess.ReadWrite))
         {
             string str = "memorystream://myXps.xps";
             Uri    uri = new Uri(str);
             PackageStore.AddPackage(uri, package);
             XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.Maximum, str);
             if (!this.AllowMultipleSignatures)
             {
                 XpsSignatureDefinition xpsSignatureDefinition = new XpsSignatureDefinition()
                 {
                     Intent        = this.SigningIntent,
                     SigningLocale = this.SigningLocation,
                     SpotId        = new Guid?(Guid.NewGuid())
                 };
                 IXpsFixedDocumentReader item = xpsDocument.FixedDocumentSequenceReader.FixedDocuments[0];
                 item.AddSignatureDefinition(xpsSignatureDefinition);
                 item.CommitSignatureDefinition();
                 X509Certificate2 digitalSignatureCertificate = this.DigitalSignatureCertificate;
                 Guid?            spotId = xpsSignatureDefinition.SpotId;
                 xpsDocument.SignDigitally(digitalSignatureCertificate, true, XpsDigSigPartAlteringRestrictions.SignatureOrigin, spotId.Value);
             }
             else
             {
                 xpsDocument.SignDigitally(this.DigitalSignatureCertificate, true, XpsDigSigPartAlteringRestrictions.None);
             }
             PackageStore.RemovePackage(uri);
             xpsDocument.Close();
         }
     }
     catch
     {
         throw;
     }
 }
Пример #9
0
        public bool showCertificate(DigitalCertificate dc)
        {
            this.IssuerNameTB.Text       = DigitalCertificate.IssuerName;
            this.SerialNumberTB.Text     = dc.SerialNumber.ToString();
            this.CertificateOwnerTB.Text = dc.SubjectName.ToString();
            this.ValidateTB.Text         = dc.IssuingDate.Date.ToString();
            this.OwnerPublicKeyTB.Text   = dc.SubjectPublicKey;
            this.Visibility = Visibility.Visible;
            this.Show();

            while (true)
            {
                if (this.okButtonClicked)
                {
                    return(true);
                }
                if (this.cancleButtonClicked)
                {
                    return(false);
                }
            }
        }
Пример #10
0
        public string SignDocument(string documentPdf, DigitalCertificate cert, PdfOptions certOptions, string pathOutput)
        {
            try
            {
                var reader  = new PdfReader(documentPdf);
                var output  = new FileStream(pathOutput, FileMode.Create, FileAccess.Write, FileShare.None);
                var stamper = PdfStamper.CreateSignature(reader, output, '\0');


                var rect       = new iTextSharp.text.Rectangle(10, 10, 0, 0);
                var appearance = stamper.SignatureAppearance;
                appearance.Reason             = "Assinatura digital";
                appearance.SignDate           = certOptions.SignDate;
                appearance.Contact            = certOptions.Contact;
                appearance.SignatureGraphic   = certOptions.SignImage;
                appearance.Location           = certOptions.Location;
                appearance.CertificationLevel = PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED;
                appearance.SetVisibleSignature(rect, 1, certOptions.NameOwnerOfCertificate);
                IExternalSignature pks = new X509Certificate2Signature(cert.Certificate, "sha-256");

                var ce    = new X509CertificateParser();
                var chain = ce.ReadCertificate(cert.Certificate.RawData);

                var lista = new List <X509Certificate> {
                    chain
                };
                ICollection <X509Certificate> lst = lista;

                MakeSignature.SignDetached(appearance, pks, lst, null, null, null, 0, CryptoStandard.CMS);
                return(pathOutput);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        protected void convertToPdfButton_Click(object sender, EventArgs e)
        {
            // Create a PDF document
            Document pdfDocument = new Document();

            // Set license key received after purchase to use the converter in licensed mode
            // Leave it not set to use the converter in demo mode
            pdfDocument.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c=";

            // Add a page to PDF document
            PdfPage pdfPage = pdfDocument.AddPage();

            try
            {
                string htmlWithDigitalSignatureMarker = htmlStringTextBox.Text;
                string baseUrl = baseUrlTextBox.Text;

                // Add a HTML string with a marker for digital signature to PDF document
                HtmlToPdfElement htmlToPdfElement = new HtmlToPdfElement(htmlWithDigitalSignatureMarker, baseUrl);
                pdfPage.AddElement(htmlToPdfElement);

                // Make the HTML element with 'digital_signature_element' mapping ID a link to digital signature properties
                HtmlElementMapping digitalSignatureMapping = htmlToPdfElement.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByMappingId("digital_signature_element");
                if (digitalSignatureMapping != null)
                {
                    PdfPage    digitalSignaturePage      = digitalSignatureMapping.PdfRectangles[0].PdfPage;
                    RectangleF digitalSignatureRectangle = digitalSignatureMapping.PdfRectangles[0].Rectangle;

                    string certificateFilePath = Server.MapPath(@"~/DemoAppFiles/Input/Certificates/evopdf.pfx");

                    // Get the certificate from password protected PFX file
                    DigitalCertificatesCollection certificates = DigitalCertificatesStore.GetCertificates(certificateFilePath, "evopdf");
                    DigitalCertificate            certificate  = certificates[0];

                    // Create the digital signature
                    DigitalSignatureElement signature = new DigitalSignatureElement(digitalSignatureRectangle, certificate);
                    signature.Reason      = "Protect the document from unwanted changes";
                    signature.ContactInfo = "The contact email is [email protected]";
                    signature.Location    = "Development server";
                    digitalSignaturePage.AddElement(signature);
                }

                // Save the PDF document in a memory buffer
                byte[] outPdfBuffer = pdfDocument.Save();

                // Send the PDF as response to browser

                // Set response content type
                Response.AddHeader("Content-Type", "application/pdf");

                // Instruct the browser to open the PDF file as an attachment or inline
                Response.AddHeader("Content-Disposition", String.Format("attachment; filename=Digital_Signatures.pdf; size={0}", outPdfBuffer.Length.ToString()));

                // Write the PDF document buffer to HTTP response
                Response.BinaryWrite(outPdfBuffer);

                // End the HTTP response and stop the current page processing
                Response.End();
            }
            finally
            {
                // Close the PDF document
                pdfDocument.Close();
            }
        }
Пример #12
0
 private void SignXml(string inputFile, string outputFile)
 {
     try
     {
         Licensing.ShowDemoMessage();
         DigitalCertificate.LogOnEToken(this.DigitalSignatureCertificate);
         DSACryptoServiceProvider dSACryptoServiceProvider = new DSACryptoServiceProvider();
         RSACryptoServiceProvider rSACryptoServiceProvider = new RSACryptoServiceProvider();
         string friendlyName = (new Oid(this.DigitalSignatureCertificate.GetKeyAlgorithm())).FriendlyName;
         if (this.DigitalSignatureCertificate.HasPrivateKey)
         {
             if (friendlyName == "DSA")
             {
                 dSACryptoServiceProvider = this.DigitalSignatureCertificate.PrivateKey as DSACryptoServiceProvider;
             }
             if (friendlyName == "RSA")
             {
                 rSACryptoServiceProvider = this.DigitalSignatureCertificate.PrivateKey as RSACryptoServiceProvider;
             }
             if (friendlyName != "DSA" && friendlyName != "RSA")
             {
                 throw new ArgumentException(CustomExceptions.XMLSigningAlgorithmNotSupported);
             }
         }
         XmlDocument xmlDocument = new XmlDocument();
         xmlDocument.Load(inputFile);
         xmlDocument.PreserveWhitespace = this.RemoveWhitespaces;
         SignedXml signedXml = new SignedXml(xmlDocument);
         if (friendlyName == "DSA")
         {
             signedXml.SigningKey = dSACryptoServiceProvider;
         }
         if (friendlyName == "RSA")
         {
             signedXml.SigningKey = rSACryptoServiceProvider;
         }
         if (this.IncludeKeyInfo || this.IncludeSignatureCertificate)
         {
             KeyInfo keyInfos = new KeyInfo();
             if (this.IncludeKeyInfo)
             {
                 if (friendlyName == "DSA")
                 {
                     keyInfos.AddClause(new DSAKeyValue(dSACryptoServiceProvider));
                 }
                 if (friendlyName == "RSA")
                 {
                     keyInfos.AddClause(new RSAKeyValue(rSACryptoServiceProvider));
                 }
             }
             if (this.IncludeSignatureCertificate)
             {
                 keyInfos.AddClause(new KeyInfoX509Data(this.DigitalSignatureCertificate.GetRawCertData()));
             }
             signedXml.KeyInfo = keyInfos;
         }
         Reference reference = new Reference();
         reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
         reference.AddTransform(new XmlDsigExcC14NTransform());
         reference.Uri = "";
         signedXml.AddReference(reference);
         signedXml.ComputeSignature();
         XmlElement xml = signedXml.GetXml();
         xmlDocument.DocumentElement.AppendChild(xmlDocument.ImportNode(xml, true));
         xmlDocument.Save(outputFile);
     }
     catch
     {
         throw;
     }
 }
        private static void signUp(AdvanceStream stream, MainWindow mainWindow)
        {
            string             digCer = stream.ReadString();
            DigitalCertificate dc     = DigitalCertificate.newClientObject(digCer);

            MainWindow.instance.Log("Get client certificate.....");
            string publicKey = "";

            MainWindow.instance.Log("connect to CA.....");


            MainWindow.clientForCertificate.connect((e) =>
            {
                e.Write("2");
            });

            publicKey = getCApublicKey(MainWindow.clientForCertificate.stream);



            KeysManager.RSAPcublicKeyOfCA = publicKey;
            MainWindow.instance.Log("CA public key", publicKey);

            if (dc.verviy())
            {
                stream.Write("1");
                byte[] encrSingUpdata   = stream.ReadBytes();
                RSA    rsa              = new RSA("Server");
                byte[] decrypSingUpData = rsa.decrypt(encrSingUpdata, KeysManager.RSAPrivateKey);

                MainWindow.instance.Log("Encrypted SignUp Data", Encoding.UTF8.GetString(encrSingUpdata));
                MainWindow.instance.Log("Decrypted SignUp Data", Encoding.UTF8.GetString(decrypSingUpData));

                SignUpObject signUpObject = SignUpObject.newLoginObject(Encoding.UTF8.GetString(decrypSingUpData));
                var          user         = DBContext.getInstace().Clients.SingleOrDefault(item => item.Username == signUpObject.username);
                if (user != null)
                {
                    if (user.Username.Equals(signUpObject.username))
                    {
                        stream.Write("0");
                        MainWindow.instance.Log("Error username already taken ", signUpObject.username);
                    }
                    else
                    {
                        stream.Write("1");
                        MainWindow.instance.Log("Error password already taken");
                    }
                }
                else
                {
                    DBContext.getInstace().Clients.Add(new Models.Client(signUpObject.name, signUpObject.username, signUpObject.password));
                    DBContext.getInstace().SaveChanges();
                    stream.Write("2");
                    user = DBContext.getInstace().Clients.SingleOrDefault(item => item.Username == signUpObject.username);
                    stream.Write(user.toJsonObject() + '\t' + "");
                    byte[] encryptKey = rsa.encrypte(KeysManager.AESkey, dc.SubjectPublicKey);
                    stream.Write(encryptKey);
                    MainWindow.instance.Log("Sign Up Successfully", user.Name);
                }
            }
            else
            {
                stream.Write("0");
            }

            MainWindow.instance.Log();
        }
        public ActionResult ConvertHtmlToPdf(IFormCollection collection)
        {
            // Create a HTML to PDF converter object with default settings
            HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();

            // Set license key received after purchase to use the converter in licensed mode
            // Leave it not set to use the converter in demo mode
            htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c=";

            // Set an adddional delay in seconds to wait for JavaScript or AJAX calls after page load completed
            // Set this property to 0 if you don't need to wait for such asynchcronous operations to finish
            htmlToPdfConverter.ConversionDelay = 2;

            Document pdfDocument = null;

            try
            {
                string htmlWithDigitalSignatureMarker = collection["htmlStringTextBox"];
                string baseUrl = collection["baseUrlTextBox"];

                // Convert a HTML string with a marker for digital signature to a PDF document object
                pdfDocument = htmlToPdfConverter.ConvertHtmlToPdfDocumentObject(htmlWithDigitalSignatureMarker, baseUrl);

                // Make the HTML element with 'digital_signature_element' mapping ID a link to digital signature properties
                HtmlElementMapping digitalSignatureMapping = htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByMappingId("digital_signature_element");
                if (digitalSignatureMapping != null)
                {
                    PdfPage    digitalSignaturePage      = digitalSignatureMapping.PdfRectangles[0].PdfPage;
                    RectangleF digitalSignatureRectangle = digitalSignatureMapping.PdfRectangles[0].Rectangle;

                    string certificateFilePath = m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/Certificates/evopdf.pfx";

                    // Get the certificate from password protected PFX file
                    DigitalCertificatesCollection certificates = DigitalCertificatesStore.GetCertificates(certificateFilePath, "evopdf");
                    DigitalCertificate            certificate  = certificates[0];

                    // Create the digital signature
                    DigitalSignatureElement signature = new DigitalSignatureElement(digitalSignatureRectangle, certificate);
                    signature.Reason      = "Protect the document from unwanted changes";
                    signature.ContactInfo = "The contact email is [email protected]";
                    signature.Location    = "Development server";
                    digitalSignaturePage.AddElement(signature);
                }

                // Save the PDF document in a memory buffer
                byte[] outPdfBuffer = pdfDocument.Save();

                // Send the PDF file to browser
                FileResult fileResult = new FileContentResult(outPdfBuffer, "application/pdf");
                fileResult.FileDownloadName = "Digital_Signatures.pdf";

                return(fileResult);
            }
            finally
            {
                // Close the PDF document
                if (pdfDocument != null)
                {
                    pdfDocument.Close();
                }
            }
        }
Пример #15
0
 public bool CreateCertificatewindows(DigitalCertificate dc)
 {
     return(cw.showCertificate(dc));
 }