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.

Nutzen Sie IronPDF heute kostenlos in Ihrem Projekt.

Erster Schritt:
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.

Häufig gestellte Fragen

Was ist ein Hardware-Sicherheitsmodul (HSM) und wozu wird es zum Signieren von PDFs verwendet?

Ein Hardware-Sicherheitsmodul (HSM) ist ein physisches Gerät zur Verwaltung digitaler Schlüssel sowie zur Durchführung von Verschlüsselungs- und Entschlüsselungsfunktionen. Es wird zum Signieren von PDFs verwendet, um die Sicherheit zu erhöhen, indem es einen sicheren und mit verschiedenen Standards konformen Signaturprozess gewährleistet.

Wie kann ich ein HSM zum Signieren von PDFs in C# konfigurieren?

Um ein HSM zum Signieren von PDFs in C# zu konfigurieren, müssen Sie das HSM mit den entsprechenden Treibern und der entsprechenden Software einrichten, sicherstellen, dass es mit Ihrem System verbunden ist, und den Signierungsprozess innerhalb Ihrer C#-Anwendung mit IronPDF konfigurieren.

Welche Schritte sind nötig, um ein PDF mit IronPDF digital zu signieren?

Um ein PDF mit IronPDF digital zu signieren, müssen Sie zuerst Ihr HSM initialisieren, die digitale Signatur in Ihrem C#-Code konfigurieren und die Signatur anschließend mithilfe der Signaturfunktion von IronPDF auf das PDF-Dokument anwenden.

Kann ich IronPDF verwenden, um PDFs mit anderen Arten von digitalen Zertifikaten zu signieren?

Ja, IronPDF unterstützt das Signieren von PDFs mit verschiedenen Arten von digitalen Zertifikaten, nicht nur mit solchen, die von einem HSM verwaltet werden. Dies schließt auch Zertifikate ein, die in Software-Keystores gespeichert sind.

Welche Vorteile bietet die Verwendung von IronPDF zum Signieren von PDFs?

IronPDF bietet eine unkomplizierte API zum Signieren von PDFs und ermöglicht so die einfache Integration digitaler Signaturen in Ihre C#-Anwendungen. Es unterstützt verschiedene Zertifikatstypen, einschließlich solcher, die von HSMs verwaltet werden, und gewährleistet dadurch Flexibilität und Sicherheit.

Ist es möglich, eine mit IronPDF erstellte PDF-Signatur zu überprüfen?

Ja, sobald ein PDF mit IronPDF signiert wurde, kann die Signatur mit gängigen PDF-Readern, die digitale Signaturen unterstützen, überprüft werden, wodurch die Integrität und Authentizität des Dokuments gewährleistet wird.

Benötige ich Programmierkenntnisse, um IronPDF zum Signieren von PDFs zu verwenden?

Für die Verwendung von IronPDF zum Signieren von PDFs werden grundlegende Programmierkenntnisse in C# empfohlen, da dies das Schreiben von Code zur Verwaltung des Signierungsprozesses und zur entsprechenden Konfiguration des HSM erfordert.

Welche Unterstützung gibt es für die Integration von HSM mit IronPDF?

Iron Software stellt Dokumentation und technischen Support bereit, um Ihnen bei der Integration von HSMs mit IronPDF zu helfen und so eine reibungslose Einrichtung und den Betrieb der digitalen Signaturfunktionen zu gewährleisten.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen
Bereit anzufangen?
Nuget Downloads 16,133,208 | Version: 2025.11 gerade veröffentlicht