How to Digitally Sign PDFs with C# using HSM

This article was translated from English: Does it need improvement?
Translated
View the article in English

Adding a signature to a PDF document is a common requirement in many applications. However, mission-critical applications require a higher level of security where the key itself cannot be tampered with. A normal signing operation with a .pfx file is akin to having a master key at your house. The application needs to load the key into your computer's memory to sign the document. If the computer itself is compromised, the key may be stolen.

A far more secure alternative is using a Hardware Security Module (HSM). With an HSM (like your USB token), the private key is generated inside the device and is physically incapable of ever leaving it.

This process is akin to bringing the document to the bank. The application provides a PIN, and the "bank manager" (the HSM) takes the document into the vault, stamps it with the key, and hands the stamped document back. The main aspect is that the key never leaves the vault. This provides an additional security measure, as the key cannot be copied or stolen.

Comience a usar IronPDF en su proyecto hoy con una prueba gratuita.

Primer Paso:
green arrow pointer

Signing with an HSM

Signing with an HSM typically requires a physical device, such as a USB token, that the application interacts with. IronPDF is fully compatible with these operations, as both the library and standard HSMs often use PKCS#11 as a common API. For demonstrative purposes regarding IronPDF's functionality with HSMs, this guide will use a simulated HSM instead of a physical one.

In a production or live testing environment, you should not use this simulation. Instead, you must use your actual HSM.

To run this simulation, you must first install SoftHSM, OpenSSL, and OpenSC to generate the necessary key and token. For more information on how to utilize SoftHSM, please refer to their public GitHub repository.

We'll start by creating a PDF from an HTML string. In the example below, we define the paths and credentials for our simulated SoftHSM. This includes providing the absolute path to the SoftHSM .dll library file and the .crt certificate file that you created.

Next, we specify the output path, which in this instance is output.pdf.

Furthermore, we define three strings: hsmTokenLabel, hsmPin, and hsmKeyLabel. These strings are case-sensitive and must exactly match the credentials you created when generating the token and certificate with SoftHSM. Afterwards, we initialize the UsbPkcs11HsmSigner object, passing the SoftHSM library path, PIN, token label, and key label as parameters.

We additionally create a PdfSignatureImage to add a visual representation of the signature onto the document. Finally, we call SignAndSave, which uses the hsmSigner we configured to sign the document and save it to the specified output path.

Code

:path=/static-assets/pdf/content-code-examples/how-to/signing-with-hsm.cs
using IronPdf;
using IronPdf.Signing;
using IronSoftware.Pdfium.Signing;
using System.Drawing;

ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Testing</h1>");

// Define Paths and Credentials
string softhsmLibraryPath = @"D:\SoftHSM2\lib\softhsm2-x64.dll";
// These MUST match what you created
string hsmTokenLabel = "MyTestToken";
string hsmPin = "123456";
string hsmKeyLabel = "my-key"; // The label for the key *inside* the token

// Create the HsmSigner object.
UsbPkcs11HsmSigner hsmSigner = new UsbPkcs11HsmSigner(
    softhsmLibraryPath,
    hsmPin,
    hsmTokenLabel,
    hsmKeyLabel
);

// Create the Signature Image
string signatureImagePath = "IronSoftware.png";
PdfSignatureImage sigImage = new PdfSignatureImage(signatureImagePath, 0, new Rectangle(50, 50, 150, 150));

// Sign PDF with HSM
pdf.SignAndSave("signedWithHSM.pdf", hsmSigner);
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

The UsbPkcs11HsmSigner additionally takes two optional parameters, the digestAlgorithm and signingAlgorithm. By default, they are set to SHA256 and RSA.

Output

Below is the output generated. As you can see, it displays the signature field and confirms that it is signed with the certificate we generated.

Output
Output Certificate

Troubleshooting

If you encounter the error shown below while running the code example, follow these troubleshooting steps to debug and verify your configuration. This CKR_GENERAL_ERROR commonly occurs when the program cannot find the SoftHSM configuration file or when the .NET application is running as a 32-bit process while the SoftHSM library is 64-bit.

General CKS error

Changing the Platform Target

A common cause for this error is an architecture mismatch. Your C# application must run as a 64-bit process to match the 64-bit SoftHSM library (softhsm2-x64.dll). In your Visual Studio project properties, change the Platform target from 'Any CPU' or 'x86' to 'x64' to ensure compatibility.

Platform Target

Setting the Environment Variable

Another common cause of error is that the program cannot find the .conf file in SoftHSM. You must tell the library where to look by setting a system-wide environment variable. Create a new variable named SOFTHSM2_CONF and set its value to the full path of your configuration file (e.g., D:\SoftHSM2\etc\softhsm2.conf). Afterwards, remember to restart Visual Studio after making the changes.

Set Environment variable

Additionally, you can verify whether the variable is found by adding this line.

Console.WriteLine($"Verifying variable: {Environment.GetEnvironmentVariable("SOFTHSM2_CONF")}");
Console.WriteLine($"Verifying variable: {Environment.GetEnvironmentVariable("SOFTHSM2_CONF")}");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

If the console output returns blank, then the program can't find the environment variable. You must set it, restart Visual Studio or your computer, and try again.

Preguntas Frecuentes

¿Qué es un módulo de seguridad de hardware (HSM) y por qué se utiliza para firmar archivos PDF?

Un Módulo de Seguridad de Hardware (HSM) es un dispositivo físico que gestiona claves digitales y realiza funciones de cifrado y descifrado. Se utiliza para firmar archivos PDF y mejorar la seguridad, garantizando que el proceso de firma sea seguro y cumpla con diversos estándares.

¿Cómo puedo configurar un HSM para firmar archivos PDF en C#?

Para configurar un HSM para firmar archivos PDF en C#, debe configurar el HSM con los controladores y el software adecuados, asegurarse de que esté conectado a su sistema y configurar el proceso de firma dentro de su aplicación C# usando IronPDF.

¿Cuáles son los pasos para firmar digitalmente un PDF usando IronPDF?

Para firmar digitalmente un PDF con IronPDF, primero debe inicializar su HSM, configurar la firma digital dentro de su código C# y aplicar la firma al documento PDF utilizando la funcionalidad de firma de IronPDF.

¿Puedo usar IronPDF para firmar archivos PDF con otros tipos de certificados digitales?

Sí, IronPDF permite firmar archivos PDF con varios tipos de certificados digitales, no solo los administrados por un HSM. Esto incluye certificados almacenados en almacenes de claves de software.

¿Cuáles son los beneficios de utilizar IronPDF para firmar PDF?

IronPDF ofrece una API sencilla para firmar archivos PDF, lo que le permite integrar fácilmente firmas digitales en sus aplicaciones C#. Admite varios tipos de certificados, incluidos los administrados por HSM, lo que garantiza flexibilidad y seguridad.

¿Es posible verificar una firma PDF creada con IronPDF?

Sí, una vez que se firma un PDF con IronPDF, la firma se puede verificar utilizando lectores de PDF estándar que admiten firmas digitales, lo que garantiza la integridad y autenticidad del documento.

¿Necesito tener experiencia en programación para utilizar IronPDF para firmar archivos PDF?

Se recomiendan conocimientos básicos de programación en C# para utilizar IronPDF para firmar archivos PDF, ya que implica escribir código para administrar el proceso de firma y configurar el HSM adecuadamente.

¿Qué tipo de soporte está disponible para integrar HSM con IronPDF?

Iron Software proporciona documentación y soporte técnico para ayudarlo a integrar HSM con IronPDF, garantizando una configuración y un funcionamiento sin problemas de las funcionalidades de firma digital.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más
¿Listo para empezar?
Nuget Descargas 16,133,208 | Versión: 2025.11 recién lanzado