PDF files are widely used in various industries, and adding digital signatures to them is a necessary security measure. Digital signatures ensure the authenticity and integrity of documents and are legally binding. This blog post will explain the process of creating a PDF digital signature service usingAzure Key VaultandSyncfusion PDF library.
Azure Key Vault is a cloud-based key management service that lets you create, store, and manage encryption keys and certificates. Syncfusion PDF Library is a .NET library that enables you to programmatically create and manipulate PDF documents. Combining these powerful tools creates a powerful and secure PDF digital signature service.
In this blog, we will follow the steps below to achieve this:
- Create an Azure Key Vault and certificate.
- Register your application to access Azure Key Vault.
- Add an access policy to Azure Key Vault.
- Create PDF Digital Signature Web API Service.
- Create Blazor WebAssembly applications using .NET 7.0.
- Start the server and call the PDF Digital Signature Service API from the client.
Create an Azure Key Vault and certificate
Let's start by creating an Azure Key Vault and certificate:
step 1:First, inAzure Portal; Please refer to thisassociate.
Step 2:Once the resource is created, go to Key Vault, selectCertificate, then clickgenerate/import.
Step 3:chooseproduceinsideCertificate Creation Methodsite.This option generates a new certificate. In this example, we selected theself-signed certificateAs the type of certificate authority.
notes:You can also import a certificate from a local device by selectingimport.
Step 4:Next, chooseAdvanced policy configuration.chooseNoIn the private key export option.
Step 5:Finally, clickcreate. The Key Vault certificate is now created under your account.
You can click and open the properties of the certificate as shown below.
Register an application to access Azure Key Vault
To access Azure Key Vault from Web API, we have to use theAzure Active Directory:
step 1:OpenAzure Active Directory.chooseapplication registrationthen clicknew registration.
Step 2:Enter your application name and proceed with registration.
After registration, you will get the following information. copyCustomer Numberandtenant numberUsed in Web API.
Step 3:choose nowAPI permissionsFrom the side menu clickAdd permissions.Select Azure Key Vault, choose Full Access, and finish the process by clickingAdd permissions.
Step 4:choosecertificates and secretsthen clicknew client secretCreate a new key. Copy this key to access it from Web API.
Add access policies to Azure Key Vault
In the previous section, we created and registered the application. We must now provide Azure Key Vault access to this newly created application:
step 1:Go to Azure Key Vault, selectaccess policy, then clickcreate.
Step 2:Select the necessary permissions and clickNext.
Step 3:In this window, select the application we created in the previous section,PDF digital signature service, then clickcreate.
The application will now be listed underaccess policypart.
Create PDF Digital Signature Web API Service
Now, let's create a web API to digitally sign PDF documents. To do this, create an ASP.NET Core minimal Web API. refer to thisassociate.
After creating the project, install the following NuGet packages as references from NuGet.org:
- Azure.Security.KeyVault.Secrets
- Azure.Identity
- Azure.Security.KeyVault.Keys
- Azure.Security.KeyVault.Certificates
- Sync Fusion.Pdf.Net.Core
Next, add a file namedSigned PDFinsideprogram.csdocument.
app.MapPost("api/signPDF", async (HttpContext context) =>{});
Certificates generated in Azure Key Vault cannot be exported or copied. However, the public part of the certificate can be obtained. We can digitally sign PDF documents using this public certificate and Azure key.
The following code retrieves the public portion of the certificate.
X509Certificate2 GetPublicCertificate(ClientSecretCredential credential, String uri){ //Create a certificate client. CertificateClient certificateClient = new CertificateClient(new Uri(uri), credential); //Get the certificate with the public key. KeyVaultCertificateWithPolicy Certificate = certificateClient.GetCertificateAsync("PDFSigner").Result; //Create and return X509Certificate2. return new X509Certificate2(certificate.Cer); }
If the certificate contains multiple certificates, such as root certificate, intermediate certificate and issuer certificate, the following code is used to build the certificate chain.
// Get the public certificate to sign the PDF document. X509Certificate2 pubCertifciate = GetPublicCertificate(credential, vaultUri); //Build certificate chain.X509Chain chain = new X509Chain();chain.Build(pubCertifciate); Listcertificates = new List ();for (int i = 0; i < chain.ChainElements.Count; i++){ certificates.Add(chain.ChainElements[i].Certificate);}
Afterwards, the external signer interface should be integrated to externally sign the hash of the PDF document with an Azure key. This interface is designed to allow retrieval of the hash of a PDF document that has been processed with a public certificate and subsequently enable signing of the document with an Azure key.
//The external signer uses Azure Key Vault.internal class ExternalSigner to sign the PDF document: IPdfExternalSigner{ public string HashAlgorithm => "SHA256"; private encryption client key client; public ExternalSigner(CryptographyClient client) { keyClient = client; } public byte[] Sign(byte[] message, out byte[] timeStampResponse) { var digest = SHA256.Create().ComputeHash(message); timestamp response=null; //Sign the hash of the PDF document return keyClient .SignAsync( SignatureAlgorithm.RS256, digest) .Result.Signature; }}
The following complete code is used to sign a PDF document with the help of external signature.
app.MapPost("api/signPDF", async (HttpContext context) =>{ var request = await context.Request.ReadFormAsync(); if (request.Files.Count>0) {
var pdfFile = request.Files[0].OpenReadStream(); // Provide your Azure Key Vault details here String tenantId = "tenantID"; String clientId = "clientID"; String secret = "secret"; String vaultUri = "vault URI"; ClientSecretCredential credential = new ClientSecretCredential(tenantId, clientId, secret); //Get the public certificate to sign the PDF document X509Certificate2 pubCertifciate = GetPublicCertificate(credential, vaultUri); //Build the certificate chain. X509Chain chain = new X509Chain(); chain.Build(pubCertifciate); Listcertificates = new List (); for (int i = 0; i < chain.ChainElements.Count; i++) { certificates.Add (chain.ChainElements[i].Certificate); } //Load the PDF document. PdfLoadedDocument loadedDocument = new PdfLoadedDocument(pdfFile); //Load an existing page. PdfLoadedPage? page = loadedDocument.Pages[0] as PdfLoadedPage; // Create a new PDF signature object PdfSignature signature = new PdfSignature(loadedDocument, page!, null, "Sig1"); signature.Bounds = new Syncfusion.Drawing.RectangleF (0, 0, 200, 100); //Create CryptographyClient with key identifier. CryptographyClient client = new CryptographyClient(new Uri("https://signature.vault.azure.net/keys/PDFSigner/adb90908592644f69e0e61bcf7c69ff4"), credential); // Sign with an external signer. signature.AddExternalSigner(new ExternalSigner(client), certificates, null); signature.Settings.DigestAlgorithm = DigestAlgorithm.SHA256; MemoryStream ms = new MemoryStream(); //Save and close the document. loadedDocument.save(ms); ms.Position = 0; loadedDocument.Close(true); context.Response.ContentType = "application/pdf"; await context.Response.Body.WriteAsync(ms.ToArray()); } });
Now that the web service has been created, it can be used in any application. For this blog, a Blazor WebAssembly (WASM) application will be developed to demonstrate the capabilities of the Web API service.
Create Blazor WebAssembly apps with .NET 7
The client application in this implementation is a Blazor WebAssembly application built using .NET version 7.0. Create a new ASP.NET Core Blazor WebAssembly application usingVisual Studio 2022, follow the guidance provided inassociate.In the application, we useHttpClient.PostAsyncmethod sends a POST request to the specified URI as an asynchronous operation.
@code { private async Task SignPDF() { //Create http HTTP client to send files and json JSON data. using (var client = new HttpClient()) { // Create multipart form data content. Use (var content = new MultipartFormDataContent()) { var document = await Http.GetByteArrayAsync("PDF_Succinctly.pdf"); content.Add(CreateContent("document", "input.pdf", document)); // call web Web API to sign PDF documents. var response = await client.PostAsync("https://localhost:7171/api/signPDF", content); if (response.StatusCode == HttpStatusCode.OK) { //Download the PDF document. var responseContent = await response.Content.ReadAsStreamAsync(); use var Content = new DotNetStreamReference(stream: responseContent); await JS.InvokeVoidAsync("SubmitHTML", "HTMLToPDF.pdf", Content); } } } } private ByteArrayContent CreateCon tent( string name, string fileName, byte[] fileBytes) { var fileContent = new ByteArrayContent(fileBytes); fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); fileContent.Headers.ContentDisposition = new ContentDispositionHeader Value("form -data") { Name = name, FileName = fileName }; return file content; }}
Call a JavaScript (JS) function once the request's response status code is OKindex.htmlfile to save the PDF document.
<脚本> window.SubmitHTML = async (fileName, contentStreamReference) => { const arrayBuffer = await contentStreamReference.arrayBuffer(); const blob = new Blob([arrayBuffer]); const url = URL.createObjectURL(blob); const anchorElement = document.createElement('a'); anchorElement.href = url; anchorElement.download = 文件名 ?? ''; anchorElement.click(); anchorElement.remove(); URL.revokeObjectURL(url);
The website will open in your default browser when you build and run the application.
Start the server and call the PDF Digital Signature Service API from the client
Next, we start the server and call the digital signature API from the client application.
step 1:Run the Web API application to launch the published Web API in the browser.
Step 2:To sign a PDF document using a client application, send an asynchronous POST request to the specified URI (For example. , https://localhost:7171/api/signPDF) on localhost. This will send the request to the server application, which will sign the PDF document using Azure Key Vault and send a response back to the client.
After successful signing, you will receive a PDF file as shown in the screenshot below.
GitHub example
For a better understanding, we haveSign PDFs with Azure Key VaultGitHub repository.
in conclusion
In this blog post we learned how to create our own PDF digital signature web service API to use Azure Key Vault andSyncfusion C# PDF Library.Now you can easily integrate this service into your application and customize it to add more functionality.
take a moment to lookdocument, where you can find additional options and features, all with code examples.
For current Syncfusion customers, the latest version of Essential Studio is available fromLicense and Download Page.
Let us know in the comments below if you have any questions about these features. You can also use oursupport forum,support portal, orFeedback Portal.We are happy to help you!
related blog
If you enjoyed this article, we think you'll also enjoy the following articles about PDF libraries:
- Digitally Sign and Verify Signatures for PDF Files Using C#: A Complete Guide
- HTML to PDF Conversion in C# - A Complete Guide
- Generate dynamic PDF reports from HTML using C#
- How to Easily Find Corrupted PDF Files in C#
- Create accessible PDF documents using C#
- The Easy Way to Edit PDFs Using C#
- 7 Ways to Compress PDF Files in C#, VB.NET
FAQs
Create a PDF Digital Signature Web Service Using Azure Key Vault and Syncfusion C# PDF Library? ›
Open the PDF document or form in Acrobat or Reader, and click Fill & Sign in the right pane. Click the Sign icon in the Fill & Sign toolbar, and then choose whether you want to add your signature or just initials. If you have already added signatures or initials, they are displayed as options to choose from.
How to create digital signature in PDF using C#? ›- Load the existing PDF document.
- Load the digital ID with a password.
- Create a signature with the loaded digital ID (this involves signing the PDF, as well).
- Save the PDF document.
- Create a new C# ASP.NET Core Web application project.
- Select Web application pattern (Model-View-Controller) for the project.
- Install the Syncfusion. Pdf. ...
- A default controller with name HomeController.
Open the PDF document or form in Acrobat or Reader, and click Fill & Sign in the right pane. Click the Sign icon in the Fill & Sign toolbar, and then choose whether you want to add your signature or just initials. If you have already added signatures or initials, they are displayed as options to choose from.
How do I create a digital signature for a PDF without Adobe? ›You can utilize the WPS Office app on a mobile device, which is accessible on both iOS and Android smartphones. Open the PDF file that has to be signed first, then launch the WPS Office app. Next, hit the "Edit" button and choose "Add Signature" from the menu that appears.
How does digital signature work in C#? ›How does a Digital Signature work? A digital signature will generate a unique value (hash / digest) from the combination of the document data and private key. During verification, the document data and public key is used to generate the exact same unique value (hash / digest).
Which software is used to insert digital signature in PDF files? ›Adobe Acrobat Reader DC is one of the best PDF signing software in our list that allows users to electronically sign PDF files within seconds only. It also allows you to edit, comment, and print the document easily.
How do I create and upload a digital signature? ›Upload your document into the electronic signature application, such as our DocuSign eSignature application. Drag in the signature, text and date fields where the recipient needs to take action. Click send. The electronic signature application will email a link to the recipient so they can access the document and sign.
Why can't I add signature to PDF? ›Security features on the PDF file itself could block signing. You can check the security options with your PDF editing software. If the file prevents signing, you may have to ask the author for an unlocked version.
How do I add a signature to a PDF without printing? ›Windows — Open the PDF in Adobe Reader and click the “Fill & Sign” button in the right pane. macOS — Open the PDF in Preview, click the Toolbox button, then click Sign. iOS — Open the PDF in Adobe Fill & Sign and tap the “sign” icon. Android — Open the PDF in Adobe Fill & Sign and tap the “sign” icon.
How do I create an electronic signature? ›
Click the 'Signatures' tab and 'add new' to create an electronic signature. Choose from the menu of three different types depending on how you want to create your signature. You can upload a file, line draw or choose a pre-formatted option. Follow this guide to How to Create an Electronic Signature to find out more.
Can any PDF be digitally signed? ›Sign a PDF. To sign a PDF document or form, you can type, draw, or insert an image of your handwritten signature. You can also add text, such as your name, company, title, or the date. When you save the document, the signature and text become part of the PDF.
Is Adobe Esignature free? ›Business moves faster with e-signatures from Adobe. Try it for free. Trusted by more than 500,000 brands around the world, Adobe helps companies drive business productivity and increase efficiency every day.
How can I create a digital signature for free? ›- Draw and scan.
- Use free online signing tools.
- Use Microsoft Word.
- PandaDoc.
- Preview (Mac)
- Acrobat Sign (formerly Adobe Sign)
- Start signing with PandaDoc.
- Frequently asked questions.
Method signatures
Methods are declared in a class, struct, or interface by specifying the access level such as public or private , optional modifiers such as abstract or sealed , the return value, the name of the method, and any method parameters. These parts together are the signature of the method.
Digital signatures are based on public key cryptography, also known as asymmetric cryptography. Using a public key algorithm -- such as Rivest-Shamir-Adleman, or RSA -- two keys are generated, creating a mathematically linked pair of keys: one private and one public.
Which algorithm to use for digital signature? ›RSA (Rivest-Shamir-Adleman)
RSA is a signature and encryption algorithm that can be used for both digital signatures and encryption.
Adobe Acrobat Reader DC is a cloud-based software designed to help businesses view, sign, and annotate PDF documents from desktops, browsers, or mobile devices. Users can create customizable forms by adding various tools such as drop-down lists, barcodes, signature fields, list boxes, and more.
Where is digital signature in PDF stored? ›All appearance data is stored in the appearances. acrodata file at %USER%\Application Data\Adobe\Acrobat\(version)\Security. Signature: A graphic that identifies the signer on the left-hand side of the appearance, such as a photo or scanned signatures.
Is a PDF signature a digital signature? ›A PDF signature can be an electronic signature or a digital signature. Creating an electronic signature in a PDF file is easy and fast and can usually be implemented with a simple click. Digital signatures can also be used to sign a PDF, but they require a digital certificate, also called digital ID.
How much does it cost to make a digital signature? ›
Rs. 750 (Inclusive of 4% Sales Tax). Any other applicable Taxes Extra.
How do I add a digital signature to a PDF using USB token? ›To sign the document using a certificate installed on the USB token you need to know the issuer common name & the serial number of the certificate, and a valid password or PIN to access the USB token. After that, you can digitally sign a PDF document using the Windows certificate store.
How do I add a digital signature block to a PDF without signing? ›- Open the PDF with Adobe Acrobat.
- Select Tools at the top left of the screen.
- In the Forms & Signature sections, choose Prepare Form.
- Select Start.
- Choose the Add a Signature block icon from the tools ribbon.
- Move your cursor to where you want to place the block and click.
You have two options for getting a digital signature: Get a digital signature from a Microsoft partner. Create your own digital signature.
What format is a digital signature file? ›When you need to request a signature, it's most common to use a PDF or Microsoft Word document, but there are many other file types that support digital signing. They can include: XLS and XLSX. PPT and PPTX.
Is DocuSign free? ›Yes, you can download the mobile app and create a free DocuSign account directly within the app to get started. Signing is always free and you can send three free signature requests with your free account.
How to create a PDF template in C#? ›- Install C# library to generate PDF from template.
- Construct HTML string with StringBuilder class.
- Populate the HTML template with stored data of Lists.
- Use RenderHtmlAsPdf method to generate PDF from the template.
- Save the generated PDF as a new document.
Creating A Digital Signature Field
Before the document can be signed, a digital signature field must be created. To create the field, click on Tools ⇨ Advanced Editing and select Digital Signature Tool. Find the signature blank on the document and draw a box over it. Click Close when the Properties box appears.
- Create ASP.NET Core project.
- Install Generate PDF in ASP.NET C# library.
- Generate PDF with intuitive APIs.
- Use URL or HTML to generate PDF document.
- Export PDF file to target place.
- Install C# Library for generating PDF files.
- Generate a PDF Document from an HTML string.
- Generate a PDF document from a URL.
- Generate PDF documents from HTML source files.
- Generate PDF documents from ASP.NET web pages.
- Add custom headers and footers to generated PDF documents.
- More...
How to export data from C# to PDF? ›
- Download and install Export to PDF C# Library.
- Explore the PdfDocument documentation to discover methods for digitally signing exported PDFs.
- Save PDF to memory using a System.IO.MemoryStream.
- Serve a PDF to the web as binary data rather than HTML.
Signature and Initials
Each signer needs to have been assigned a required Signature field. If a signer does not have a required signature field assigned, or has only been assigned an optional signature field, Adobe Acrobat Sign adds a Signature block at the bottom of the document.
- To create your new signature, mouse over your name in the upper-right corner of the window. ...
- Click the Create button.
- The signature panel is exposed, allowing you to enter your signature. ...
- When you have a signature you like, click Apply. ...
- Follow the same process to save your initials.
- Open a PDF file in Acrobat.
- Click the Fill & Sign tool in the right pane.
- Add a recipient: Enter an email address and add a custom message if you want. ...
- Create your form and signature fields: ...
- Send your form: