Signature Library (SignLib) User Manual

How to create and verify digital signatures from .NET code: PDF (PAdES), CAdES / PKCS#7 (.p7m, .p7s), XMLDSig and XAdES, Office documents and ASiC-E containers, with time stamps, long term validation data and certificates from files, from the Windows store, from smart cards and from HSMs.

Who this manual is for

For .NET developers who add digital signatures to an application, a service or a script. You should know C# or VB.NET and what a digital certificate is. The concepts of electronic signatures are explained where they change what you write in code. Each chapter has a reference part (the properties and the methods, with their defaults) and examples that you can paste in a project.

1. Introduction

1.1 What the library is

SignLib, the Signature Library, is a single managed assembly (SignLib.dll) that creates and verifies electronic signatures. It does not need Adobe software, Microsoft Office, the Windows cryptographic UI or any native component: the documents are processed in memory, by your own process, and the library writes no temporary files. The library is written in C#. The structure of the PDF documents is read and written with a modified version of iTextSharp 4.1.6, and the cryptographic structures with Bouncy Castle C# 2.7.0. Both are compiled into SignLib.dll, so it is the only file of the library that your application needs. Their types are internal: the public API has only the SignLib namespaces, and an application can use the Bouncy Castle NuGet package next to SignLib without conflicts. The licenses of these components are in Appendix D.

The classes of the library, grouped by what they do:

TaskClassesWhat you get
Sign a PDF documentPdfSignaturePKCS#7 (adbe.pkcs7.detached) and PAdES signatures (ETSI.CAdES.detached): B-B, B-LT and B-LTA; visible or invisible; certification signatures; signature fields; document time-stamps. section 6
Encrypt, merge and change PDF documentsPdfEncrypt, PdfMerge, PdfInsertObjectPassword and certificate encryption, merging, text and images added to the pages. section 6.10
Sign any file as CMS / CAdESCadesSignature, CadesVerify.p7m (attached) and .p7s (detached) files: CMS, CAdES-BES (B-B), CAdES-T (B-T), -C, -X Long, -A, B-LT and B-LTA; co-signatures. section 7
Sign XML documentsXmlSignature, XadesSignatureEnveloped XMLDSig with RSA or ECDSA; XAdES B-B, B-T, B-LT and B-LTA, enveloped or detached. section 8
Sign Office documentsOfficeSignaturePackage signatures of .docx, .xlsx, .pptx (and the macro-enabled types), invisible or visible (signature lines in Word). section 9
Container with signed filesAsicSignatureASiC-E (.asice) containers with XAdES signatures. section 10
Time-stampsTimestampClient, TimestampSettings, TimestampInfoRFC 3161 time-stamps for signatures and for files (.tsr, .tst, .tsd), and their verification. section 11
CertificatesDigitalCertificate, X509CertificateGeneratorLoad certificates (PFX, Windows store, smart cards), check their validity and revocation (CRL, OCSP), generate self-signed, CA and end-user certificates and certificates for a CSR. section 5
Keys outside the applicationIExternalSignatureSigning with PKCS#11 tokens, HSMs, cloud key vaults and remote signing services, in one step or in two phases. section 13

1.2 Supported platforms

The library is built from one source tree for .NET 8, .NET 9, .NET 10, .NET 11 and .NET Framework 4.6.2 or later. There is one SignLib.dll for every platform, in its own folder of the folder SignLib of the download:

Your projectFolder of the library
.NET 8SignLib\net8.0
.NET 9SignLib\net9.0
.NET 10SignLib\net10.0
.NET 11SignLib\net11.0
.NET Framework 4.6.2 to 4.7.xSignLib\netframework4.6.2
.NET Framework 4.8 and 4.8.1SignLib\netframework4.8

Use the assembly that matches the target framework of your project. All the builds have the same public API. The files of every folder are listed in section 2.1.

The signing and verification code is managed and it does not depend on the operating system. Some functions use the Windows APIs and they are available only on Windows:

FunctionWindows only because
Selecting a certificate in a window (DigitalCertificate.LoadCertificate without a criterion)It shows the Windows certificate selection dialog.
Certificates of the Windows store and of the smart cards that Windows exposes (CAPI/CNG)The Windows certificate stores. On the other systems load a PFX file or use a PKCS#11 module (section 13).
Setting the PIN of a smart card key (DigitalCertificate.SmartCardPin, SmartCardPinExtensions.SetPinForPrivateKey)CNG and CAPI keys (PlatformNotSupportedException on Linux and macOS).
Visible signatures of Office documents (signature lines)The images of the signature lines are drawn with System.Drawing (PlatformNotSupportedException on the other systems).
CRL download from an LDAP URL (VerificationType.LDAP)System.DirectoryServices.

1.3 How the manual is organized

  1. section 2 shows how to add the library to a project and how to register it. section 3 signs and verifies a PDF document in a few lines.
  2. section 4 describes what is common to all the signature classes: the usage pattern, the hash algorithms, the signature levels, what “valid” means, the exceptions, the threads and the network access. Read it once.
  3. section 5 explains the certificates; then one chapter for every kind of document: section 6, section 7, section 8, section 9, section 10.
  4. section 11, section 12 and section 13 are about the features that every format shares.
  5. section 14 explains what the library gives for eIDAS signatures. section 15 shows complete solutions: services, batches, parallel signing, two-phase signing over HTTP. section 16 lists the sample projects.
  6. section 17 lists the errors you can meet and what to do. section 18 is the reference of all the public types and members.

1.4 Conventions

Not legal advice

The manual explains the technical side of the electronic signatures of the eIDAS Regulation (EU) 910/2014. Whether a signature has the legal effect of a qualified electronic signature depends on the certificate, on the device that holds its key and on the law that applies to you, not on the library. See section 14.

2. Installation and project setup

2.1 What is delivered

FilePurpose
SignLib.dllThe library, a single file: it needs no other DLL of the download. There is one build for every platform, in the folders SignLib\net8.0, SignLib\net9.0, SignLib\net10.0, SignLib\net11.0, SignLib\netframework4.6.2 and SignLib\netframework4.8 (section 1.2). The assembly is strong-named (version 8.6.0.0, public key token ffdaa12fb4cf4a55).
SignLib.xmlThe documentation of the members. Keep it next to SignLib.dll: Visual Studio shows it as IntelliSense (summaries, parameters, exceptions).
SignLib.deps.jsonThe .NET builds only: the list of the NuGet packages that the library uses. Keep it in the same folder as SignLib.dll.
SignLib.pdbThe .NET builds only: the debugging symbols. It is not needed to run the library.
THIRD-PARTY-NOTICES.txtIn the folder License Agreement: the copyright notices and the license conditions of the open source components compiled into SignLib.dll. Distribute it with your application (section 2.6). The same text is embedded in SignLib.dll, as the resource SignLib.THIRD-PARTY-NOTICES.txt.
License Agreement folderThe license of the library, the licenses of the open source components (Third-Party Licenses) and the source code of the iTextSharp files compiled into the library (Source Code). See Appendix D.
Sample projectsOne folder for .NET (NET Sample Projects) and one for .NET Framework 4.6.2 (NET Framework Sample Projects), each with its own copy of the library in the folder SignLib. See section 16.
PowerShell ScriptsScripts that sign and verify documents from Windows PowerShell 5.1, with a copy of the .NET Framework 4.6.2 build of SignLib.dll (section 3.3).

The library has no installer and no native files. To install it, copy the files of the folder that matches your platform into a folder of your solution and reference SignLib.dll.

2.2 A .NET 8, .NET 9, .NET 10 or .NET 11 project

Reference the assembly with a HintPath and add the NuGet packages that the library uses. The library is referenced as a file, so the packages that it uses are not added automatically: add them to your project, version 10.0.15 or newer (the version that the library was built with; it is the same for .NET 8, .NET 9, .NET 10 and .NET 11). Use the build of the library in the folder that matches your target framework: net8.0, net9.0, net10.0 or net11.0, and keep SignLib.deps.json next to SignLib.dll:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <OutputType>Exe</OutputType>
  </PropertyGroup>
  <ItemGroup>
    <!-- Used by every signature class -->
    <PackageReference Include="System.Security.Cryptography.Pkcs" Version="10.0.15" />
    <PackageReference Include="System.Security.Cryptography.Xml" Version="10.0.15" />
    <PackageReference Include="System.Windows.Extensions" Version="10.0.15" />
    <!-- Office signatures (and the images of the signature lines), and the LDAP downloads of CRLs -->
    <PackageReference Include="System.IO.Packaging" Version="10.0.15" />
    <PackageReference Include="System.Drawing.Common" Version="10.0.15" />
    <PackageReference Include="System.DirectoryServices" Version="10.0.15" />
  </ItemGroup>
  <ItemGroup>
    <Reference Include="SignLib">
      <HintPath>..\SignLib\SignLib.dll</HintPath>
    </Reference>
  </ItemGroup>
</Project>
PackageNeeded for
System.Security.Cryptography.Pkcs, System.Security.Cryptography.Xml, System.Windows.ExtensionsAll the projects: CMS / CAdES and PDF signatures, XML signatures, the certificate dialogs.
System.IO.Packaging, System.Drawing.CommonOffice documents: the package parts, and the images of the signature lines. Not needed by the PDF, CAdES, XML, XAdES and ASiC-E classes.
System.DirectoryServicesDownloading CRLs from an LDAP address (Windows).
Pkcs11Interop (not a dependency of the library)Only in the samples that talk to a PKCS#11 module: the sample class Pkcs11ExternalSignature uses it (section 13.3).

In Visual Studio the same is done with Project > Add Project Reference > Browse, selecting SignLib.dll, and with Manage NuGet Packages.

2.3 A .NET Framework 4.6.2 (or later) project

Add the reference to the .NET Framework build of SignLib.dll: the folder SignLib\netframework4.6.2 for a project that targets .NET Framework 4.6.2 to 4.7.x, the folder SignLib\netframework4.8 for .NET Framework 4.8 and 4.8.1:

<ItemGroup>
  <Reference Include="SignLib, Version=8.6.0.0, Culture=neutral, PublicKeyToken=ffdaa12fb4cf4a55, processorArchitecture=MSIL">
    <SpecificVersion>False</SpecificVersion>
    <HintPath>..\SignLib\SignLib.dll</HintPath>
  </Reference>
  <Reference Include="System" />
  <Reference Include="System.Drawing" />
  <Reference Include="System.Security" />
  <Reference Include="System.Xml" />
</ItemGroup>

The other assemblies that the library uses (WindowsBase for the Office documents, System.IO.Compression for the ASiC-E containers, System.DirectoryServices for the LDAP downloads of CRLs) are part of .NET Framework: add a reference to them only when your own code uses their types. The source code of the library is C# 7.3, so every public member can be used from a .NET Framework 4.6.2 project with the language version of that framework. No NuGet package is needed on .NET Framework.

TLS on .NET Framework

The time-stamp, OCSP and CRL requests use HttpWebRequest on .NET Framework. The TLS versions can be set only for the whole application (ServicePointManager.SecurityProtocol). Before its first request, the library adds TLS 1.2 to the versions of the application (and TLS 1.0 and 1.1 while NetworkSettings.AllowLegacyTls is true, the default), only when the application does not leave the choice to the operating system; it never removes a version of the application. If a server accepts TLS 1.2 only and a request fails, set ServicePointManager.SecurityProtocol yourself at the start of the program. On .NET the requests are sent with a HttpClient of the library, and its TLS settings do not affect the rest of the application.

2.4 The serial number

Every class that creates or verifies signatures takes the serial number of the library as the parameter of its constructor:

const string LibrarySerialNumber = "YourSerialNumber";

PdfSignature pdfSignature = new PdfSignature(LibrarySerialNumber);
CadesSignature cadesSignature = new CadesSignature(LibrarySerialNumber);
XadesSignature xadesSignature = new XadesSignature(LibrarySerialNumber);
Where to keep the serial number

The samples keep it in a constant, to stay short. In an application read it from the configuration (a settings file, an environment variable, a secret store) and pass it to the constructors. The serial number is not a secret of the signed documents, but it identifies your license: do not publish it in a public repository.

string serialNumber = Environment.GetEnvironmentVariable("SIGNLIB_SERIAL");   // null: the demo version
PdfSignature pdfSignature = new PdfSignature(serialNumber);

2.5 Check the installation

A program that prints the version of the assembly and signs nothing:

using System;
using SignLib.Pdf;

class Program
{
    static void Main()
    {
        // The assembly of any public class of the library.
        System.Reflection.AssemblyName name = typeof(PdfSignature).Assembly.GetName();
        Console.WriteLine(name.Name + " " + name.Version);
        Console.WriteLine("Runtime: " + Environment.Version);
    }
}

If the program starts, the assembly and its dependencies are found. The most frequent mistakes at this point are in section 17 (a NuGet package that is missing, the wrong build for the target framework).

2.6 Deployment

SignLib.dll contains a modified version of iTextSharp 4.1.6 (Mozilla Public License 1.1) and Bouncy Castle C# 2.7.0 (MIT license), compiled from their source code; see Appendix D.

3. Quick start

This chapter signs a PDF document with a certificate from a PFX file and verifies the result, in C#, in VB.NET and in PowerShell. It uses the files of the sample projects: source.pdf and cert.pfx (a self-signed test certificate, the password is 123456). Replace YourSerialNumber with your serial number (section 2.4).

3.1 Sign and verify a PDF document

using System;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using SignLib.Certificates;
using SignLib.Pdf;

class Program
{
    private const string LibrarySerialNumber = "YourSerialNumber";

    static void Main()
    {
        // 1. The signing certificate, with its private key, from a PFX file.
        X509Certificate2 certificate = DigitalCertificate.LoadCertificate("cert.pfx", "123456");

        // 2. Load the document and set the signature.
        PdfSignature pdfSignature = new PdfSignature(LibrarySerialNumber);
        pdfSignature.LoadPdfDocument("source.pdf");
        pdfSignature.DigitalSignatureCertificate = certificate;
        pdfSignature.SigningReason = "I approve this document";
        pdfSignature.SignaturePosition = SignaturePosition.TopLeft;

        // 3. Sign: the result is the signed PDF document.
        byte[] signedPdf = pdfSignature.ApplyDigitalSignature();
        File.WriteAllBytes("source[signed].pdf", signedPdf);

        // 4. Verify: load the signed document and read its signatures.
        PdfSignature verifier = new PdfSignature(LibrarySerialNumber);
        verifier.LoadPdfDocument(signedPdf);

        foreach (PdfSignatureInfo info in verifier.DocumentProperties.DigitalSignatures)
        {
            Console.WriteLine(info.SignatureName + ": signed by " + info.SignatureCertificate.GetNameInfo(X509NameType.SimpleName, false)
                + ", intact: " + info.SignatureIsValid);
        }
    }
}

What the code does:

  1. DigitalCertificate.LoadCertificate(file, password) returns an X509Certificate2 with the private key. Other sources are in section 5.2.
  2. A PdfSignature object holds the settings of the signature. You load the document, set the certificate and the options of the visible signature.
  3. ApplyDigitalSignature() returns the signed document as a byte[]. The library never overwrites the input file.
  4. The verification is done with the same class. SignatureIsValid says that the document was not changed after it was signed and that the signature value matches the certificate in the signature. It does not say that you can trust the signer: see section 4.5.

3.2 The same in VB.NET

Imports System
Imports System.IO
Imports System.Security.Cryptography.X509Certificates
Imports SignLib.Certificates
Imports SignLib.Pdf

Module Program
    Private Const LibrarySerialNumber As String = "YourSerialNumber"

    Sub Main()
        Dim certificate As X509Certificate2 = DigitalCertificate.LoadCertificate("cert.pfx", "123456")

        Dim pdfSignature As New PdfSignature(LibrarySerialNumber)
        pdfSignature.LoadPdfDocument("source.pdf")
        pdfSignature.DigitalSignatureCertificate = certificate
        pdfSignature.SigningReason = "I approve this document"
        pdfSignature.SignaturePosition = SignaturePosition.TopLeft

        Dim signedPdf As Byte() = pdfSignature.ApplyDigitalSignature()
        File.WriteAllBytes("source[signed].pdf", signedPdf)

        Dim verifier As New PdfSignature(LibrarySerialNumber)
        verifier.LoadPdfDocument(signedPdf)

        For Each info As PdfSignatureInfo In verifier.DocumentProperties.DigitalSignatures
            Console.WriteLine(info.SignatureName & ": intact: " & info.SignatureIsValid.ToString())
        Next
    End Sub
End Module

All the examples of this manual are in C#; the VB.NET code is the same calls with the syntax of the language. The sample set for .NET Framework contains a complete VB.NET project (section 16).

3.3 The same in PowerShell

Windows PowerShell 5.1 runs on .NET Framework, so it uses the .NET Framework build of the library (the folder PowerShell Scripts of the download has a copy of it). SignLib.dll is the only file to load:

$dir = $PSScriptRoot
[Reflection.Assembly]::LoadFrom("$dir\SignLib.dll") | Out-Null

$serial      = "YourSerialNumber"
$certificate = [SignLib.Certificates.DigitalCertificate]::LoadCertificate("$dir\cert.pfx", "123456")

$signature = New-Object SignLib.Pdf.PdfSignature($serial)
$signature.LoadPdfDocument("$dir\source.pdf")
$signature.DigitalSignatureCertificate = $certificate
$signature.SigningReason = "I approve this document"
[IO.File]::WriteAllBytes("$dir\source[signed].pdf", $signature.ApplyDigitalSignature())

$check = New-Object SignLib.Pdf.PdfSignature($serial)
$check.LoadPdfDocument("$dir\source[signed].pdf")
foreach ($info in $check.DocumentProperties.DigitalSignatures) {
    "{0}: intact = {1}" -f $info.SignatureName, $info.SignatureIsValid
}

Run it with powershell.exe -File sign.ps1. Enumerations are written [SignLib.Pdf.SignaturePosition]::TopLeft. PowerShell 7 (pwsh.exe) runs on .NET and cannot load the .NET Framework build. The scripts of the folder PowerShell Scripts (signing PDF, CAdES, XAdES and Office documents, a folder, the verification, the renewal of a PAdES-LTA time-stamp) are written for Windows PowerShell 5.1; read How to Use the PowerShell Scripts.txt in that folder.

3.4 Sign any file as .p7m

The same pattern with CadesSignature signs a file of any type; the result is a .p7m file that contains the file and its signature. CadesVerify verifies it and returns the signers and the original file:

CadesSignature cadesSignature = new CadesSignature(LibrarySerialNumber);
cadesSignature.DigitalSignatureCertificate = signingCertificate;

File.WriteAllBytes("test.txt.p7m", cadesSignature.ApplyDigitalSignature("test.txt"));

CadesVerify cadesVerify = new CadesVerify("test.txt.p7m", LibrarySerialNumber);

foreach (CadesSignatureInfo signer in cadesVerify.Signatures)
    Console.WriteLine(signer.SignatureCertificate.Subject + ", intact: " + signer.SignatureIsValid);

File.WriteAllBytes("test.txt.verified", cadesVerify.UnsignedDocument);   // the signed file, extracted

The XML, Office and ASiC-E classes follow the same pattern: set the certificate and the level, call ApplyDigitalSignature, and verify with VerifyDigitalSignature (section 8, section 9, section 10).

What to read next
  • The common behavior of all the classes: section 4.
  • Certificates from the Windows store, from a smart card or from a key vault: section 5 and section 13.
  • A signature that stays valid for years (time-stamp, validation data): section 12.
  • Complete samples to run: section 16.

4. Concepts common to all the signature classes

This chapter describes what you need to know once, before the chapters about the formats: the usage pattern of the classes, the hash algorithms, the signature levels, what a verification result means, the exceptions, the threads, the network access and the limits applied to the documents that are read.

4.1 The usage pattern

Every format has a class that signs (and, for most formats, verifies) with the same steps:

  1. create the object with the serial number of the library;
  2. set the signing certificate (DigitalSignatureCertificate) and the options of the signature (properties);
  3. call ApplyDigitalSignature;
  4. to verify, call VerifyDigitalSignature, or read the information of the signatures.

The objects keep their settings between the calls, so you can set the certificate and the options once and sign many documents with the same object (but not from several threads at the same time, section 4.9). The signing methods return the signed document or write it to the output you give; they never change the input.

ClassDocument inSigning methodResult
PdfSignatureLoadPdfDocument(string | byte[] | Stream | Uri)ApplyDigitalSignature(), ApplyDigitalSignature(Stream output)byte[], the signed PDF, or the signed PDF written to the output stream
CadesSignaturethe parametersApplyDigitalSignature(string file | byte[] data), ApplyDigitalSignature(Stream in, Stream out)byte[], the .p7m (or the .p7s of a detached signature), or the signature written to the output stream
XmlSignaturethe parametersApplyDigitalSignature(string in, string out), ApplyDigitalSignature(Stream in, Stream out)the signed XML, written to the output
XadesSignaturethe parametersApplyDigitalSignature(string in, string out)the signed XML, or the signature file (detached)
OfficeSignaturethe parametersApplyDigitalSignature(string in, string out), (byte[]), (Stream)the signed document
AsicSignaturethe filesCreateContainer(...), AddSignature(...)the .asice container

The classes that sign XML and Office documents write the result to the output file, and delete a partially written output file when the signature fails (the input file is never deleted: the input and the output can be the same file).

4.2 Formats and standards

ClassSignatureStandard
PdfSignaturePKCS#7 detached (adbe.pkcs7.detached); PAdES B-B, B-LT and B-LTA (ETSI.CAdES.detached with the document security store)ISO 32000-1 (PDF), ETSI EN 319 142-1 (PAdES), RFC 5652 (CMS)
CadesSignatureCMS / PKCS#7; CAdES-BES, -C, -X Long, -A, B-LT, B-LTA; attached (.p7m) or detached (.p7s)RFC 5652, ETSI EN 319 122-1 (CAdES), ETSI TS 101 733
XmlSignatureXMLDSig enveloped, RSA or ECDSAW3C XML Signature, RFC 6931 (ECDSA)
XadesSignatureXAdES B-B, B-T, B-LT, B-LTA; enveloped or detachedETSI EN 319 132-1
OfficeSignatureOffice Open XML package signatures with XAdES properties (B-B, B-T, B-LT)ECMA-376 Part 2, [MS-OFFCRYPTO]
AsicSignatureASiC-E container with XAdES signatures (B-B, B-T, B-LT, B-LTA)ETSI EN 319 162-1
TimestampClientRFC 3161 time-stamps: .tsr, .tst, .tsdRFC 3161, RFC 5544 (TimeStampedData)

4.3 Hash algorithms

The enumeration HashAlgorithm has SHA1, SHA256, SHA384 and SHA512. Every signature class has a HashAlgorithm property; the default is SHA-256. The time-stamp requests have their own setting (TimestampSettings.HashAlgorithm, default SHA-256).

4.4 Signature levels

The ETSI standards define profiles of increasing durability. They are called B-B (basic), B-T (with a time-stamp), B-LT (with long term validation data) and B-LTA (with archival time-stamps). The names of the levels differ in the libraries of the classes, but the idea is the same:

B-Bsignature + signing certificate B-T+ time-stamp of the signature B-LT+ certificates, CRLs, OCSP B-LTA+ archive time-stamp PDF Pades (or Default = PKCS#7)+ TimeStamping.ServerUrlPadesLTPadesLTA CAdES CadesBes (or Cms)CadesTCadesLT (CadesC, CadesXL)CadesLTA (CadesA) XAdES, Office, ASiC-E XadesBXadesTXadesLTXadesLTA (not for Office)
The levels of a signature and the property values that create them. The details are in the chapters of the formats and in section 12.

A signature is created at the level that you ask for, or not at all: when the validation data of a B-LT or B-LTA signature cannot be obtained, the signing throws ValidationDataException and no document is written (section 12.4). The level that a signature really has is read from the signature: the Level property (the enumeration SignatureLevel: None, B, T, LT, LTA) of PdfSignatureInfo, CadesSignatureInfo, XadesSignatureInfo and OfficeSignatureInfo. It is determined from what the signature contains, by the rules of the ETSI baseline profiles; None means that the signature is not an AdES signature (for example a PKCS#7 signature without the signing-certificate attribute, an XMLDSig signature without the XAdES properties, a document time-stamp) or that it is not valid.

4.5 What “valid” means

The verification methods of the library (PdfSignatureInfo.SignatureIsValid, CadesSignatureInfo.SignatureIsValid, XmlSignature.VerifyDigitalSignature, XadesSignature.VerifyDigitalSignature, OfficeSignature.VerifyDigitalSignature, AsicSignature.VerifyDigitalSignature) answer one question: is the signature intact? They verify that

When SignatureIsValid is false, read SignatureAlgorithmNotSupported (PdfSignatureInfo, CadesSignatureInfo): true means that the signature uses an algorithm that the library does not support, so it could not be verified, but it was not found altered.

They do not verify that you can trust the signer. A complete verification has more questions, and each one has its own tool:

QuestionHow to answer it
Is the signature intact?SignatureIsValid, VerifyDigitalSignature.
Was the certificate valid when the document was signed (period of validity)? Was it revoked? Does its chain end in a root that you trust?CertificateValidator.Validate (section 5.4). With the information of a signature (PdfSignatureInfo, CadesSignatureInfo, XadesSignatureInfo) it validates the certificate at the time of the time-stamp (or now, without a time-stamp): the chain, the validity periods, the revocation status, from the validation data embedded in the signature and then online, and the key usage. The trusted roots are a decision of the application: the roots of Windows and/or your own list (CertificateValidationSettings.TrustedRoots).
Which level does the signature have, and does it contain its validation data?Level, ValidationDataComplete and MissingValidationData of the signature information (section 12.4).
Is the time reliable?The time-stamp of the signature (TimestampInfo), and the certificate of the time-stamping authority.
Is the signature qualified, and which level is it in eIDAS?An eIDAS validation service (for example the EU DSS validator) with the EU trusted lists. section 14. CertificateValidator does not use the trusted lists. What the certificate declares about itself is read with DigitalCertificate.GetQualifiedCertificateInfo (section 14.4); the free .NET eIDAS Certificate Validator tells you, from the trusted lists, if the certificate is qualified and which qualified trust service branch its issuer belongs to.
Do not show “valid” to the user from SignatureIsValid alone

A self-signed certificate created in a minute produces signatures that are intact. If your application shows the result to a person, add the checks of the certificate (CertificateValidator) and say what was verified. A full verification routine is in section 6.11. If Adobe shows the signature as validity unknown while the signature is intact, see “Signature validity is unknown” in Adobe: causes and solutions.

4.6 The time of a signature

Signatures have two different times, and the property names say which one you read:

PdfSignatureInfo.SignatureTime returns the time of the time-stamp when the signature has one, and the time declared by the signer otherwise (check SignatureIsTimestamped).

4.7 Files, byte arrays and streams

The library works in memory and writes no temporary files: the only files that it writes are the output files that you give to it, and its caches (certificate chains, private keys, revocation data, section 5.5, section 12.5) are kept in memory only. It can run in a container or in a service with a read-only file system. (The import of a PFX file is done by the platform, which on Windows may use a temporary key container: section 5.2.)

A document given as a file or as a byte array is read completely, processed and returned as byte[] (or written to the output you give). Plan the memory of your process for the size of the documents and for the number of documents that you sign in parallel. The classes that sign XML and Office documents and the ASiC-E container have overloads for byte arrays and streams; use them in a web application, so that the documents do not touch the disk.

The PDF and the CAdES signatures can be created without holding the document in memory, for large documents:

A complete example is in section 15.7.

PdfSignature.LoadPdfDocument(Uri) downloads the document with an HTTP request; the time-out of the download is NetworkSettings.RevocationTimeout, and a document larger than NetworkSettings.MaxResponseSize (50 MB by default) is refused (section 4.10).

4.8 Exceptions

The methods of the library throw the standard .NET exceptions, and a few exceptions of their own that derive from them; the message describes the cause. These are the ones that you should expect, with their usual causes:

ExceptionWhen
NullReferenceExceptionThe signing certificate (Digital certificate is not set.) or the document (Document is not loaded.) was not set before the call, or a level that needs a time-stamp has no time-stamping server (Time Stamp Server URL must be set.). The library uses this exception for these mistakes of the caller.
ArgumentException, ArgumentNullException, ArgumentOutOfRangeExceptionA parameter or a property has a value that is not valid: a missing value, a page that does not exist (Invalid signature page number.), a name or a URL that is not valid, a serial number that cannot be checked.
FileNotFoundExceptionAn input file does not exist.
IOExceptionA PDF document of 2 GB or more (section 4.7).
CryptographicExceptionThe signature, the certificate or the document cannot be processed: no private key, the key cannot be used, a PIN is wrong, the file is not a CMS signature, a signature does not fit in the space reserved for it, a PFX file cannot be loaded, a password is wrong, an already signed PDF document is encrypted, an ASiC-E container whose mimetype entry is not valid. Most of the errors of the signature creation are reported with this type.
ValidationDataException (SignLib.Certificates, derives from CryptographicException)A long term signature (PAdES-LT/LTA, CAdES-LT/LTA/C/XL/A, XAdES-LT/LTA, ASiC-E, Office XAdES-LT) was requested and the revocation data (OCSP response or CRL) of a certificate of the signer or of the time-stamping authority cannot be obtained. No document is produced. MissingData lists the certificates and the reasons (section 12.4).
CertificateRevokedException (SignLib.Certificates, derives from CryptographicException)A certificate of the chain of the signer or of the time-stamping authority is revoked (an OCSP response “revoked”, or a CRL that lists it), found when the library collects revocation data: the long term levels, the PDF signatures with revocation data (PadesLtvLevel not None), RevocationCache.Prefetch. No document is produced. Certificate, RevocationTime, RevocationReason and IsTimestampAuthority give the details. AllowIncompleteValidationData does not apply to it.
SecurityLimitException (SignLib)A ZIP container (ASiC-E) or an Office package exceeds a limit of SecurityLimits, or it has duplicate entries (section 4.11).
XmlExceptionAn XML document cannot be read, for example a document with a DTD (section 4.11).
WebExceptionThe time-stamping server did not answer, it answered with an error or its response is not valid (Invalid time stamping response. and the details); a download (a document from a URL) failed; a response is larger than NetworkSettings.MaxResponseSize, or a request has too many redirects (section 4.10). The OCSP and CRL downloads of the long term signatures do not throw it: a failure is reported in ValidationDataException.
NotSupportedExceptionThe combination of options is not supported: SHA-1 for a new XML, XAdES, Office or ASiC-E signature, the level XAdES-LTA for an Office document.
InvalidOperationExceptionThe operation is not allowed in the state of the document or with the options: for example a signature line added to an Office document that is already signed, a long term level with the revocation data set to None (PadesLtvLevel, LtvLevel), a PAdES-LT signature without a time-stamping server.
PlatformNotSupportedExceptionA function that needs Windows, on another operating system (section 1.2).

Catch the exceptions at the level where you can act on them, and show or log ex.Message. The library reports the original failure as the message or as the inner exception. Catch the derived exceptions before CryptographicException. When the signing of a file fails, the partial output file is deleted (the original is never deleted).

try
{
    PdfSignature pdfSignature = new PdfSignature(LibrarySerialNumber);
    pdfSignature.LoadPdfDocument("source.pdf");
    pdfSignature.DigitalSignatureCertificate = signingCertificate;
    pdfSignature.SignatureStandard = PdfSignatureStandard.PadesLT;
    pdfSignature.TimeStamping.ServerUrl = new Uri("https://ca.signfiles.com/TSAServer.aspx");

    File.WriteAllBytes("source[signed].pdf", pdfSignature.ApplyDigitalSignature());
}
catch (CertificateRevokedException ex)
{
    // A certificate of the signer or of the time-stamping authority is revoked: do not retry with this certificate.
    Console.WriteLine("Revoked: " + ex.Certificate.Subject + " since " + ex.RevocationTime + " (" + ex.RevocationReason + ")");
}
catch (ValidationDataException ex)
{
    // An OCSP response or a CRL could not be obtained: retry later.
    foreach (MissingValidationData missing in ex.MissingData)
        Console.WriteLine("No revocation data for " + missing.Subject + ": " + missing.Reason);
}
catch (WebException ex)
{
    // The time-stamping server is not reachable: retry later or use another server.
    Console.WriteLine("Time-stamp: " + ex.Message);
}
catch (CryptographicException ex)
{
    // The key, the certificate or the document cannot be used.
    Console.WriteLine("Signature: " + ex.Message);
}

4.9 Threads and static state

A complete example of parallel signing is in section 15.3.

4.10 Network access

The library opens network connections only for these functions:

FunctionConnection
Signatures with a time-stamp (TimeStamping.ServerUrl set), B-T and higher levels, TimestampClientHTTP POST to the time-stamping server (RFC 3161). Time-out: TimestampSettings.ServerTimeout, 20 seconds by default.
Revocation data of the signatures: the long term levels (PAdES-LT/LTA, CAdES C, X Long, A, LT and LTA, XAdES-LT/LTA, ASiC-E, Office XAdES-LT), and the PDF signatures while PadesLtvLevel is not None (the default is IncludeOcspOnly: a PDF signature contains the revocation data of the signer)OCSP requests and CRL downloads, from the addresses written in the certificates of the chains of the signer and of the time-stamping authority. The data is reused from RevocationCache (section 12.5). The certificates of the issuers that are not on the computer are downloaded by the certificate chain engine of the platform (section 5.2).
CertificateValidator.Validate (UseOnlineRevocation), DigitalCertificate.VerifyDigitalCertificate with OCSP, CRL or LDAPHTTP (or LDAP) to the addresses of the certificate.
PdfSignature.LoadPdfDocument(Uri), PdfEncrypt.LoadPdfDocument(Uri)HTTP GET of the document.

A signature without a time-stamp and without revocation data (for a PDF signature: PadesLtvLevel = PadesLtvLevel.None), and the verification of a signature, do not use the network. The requests use the user agent SignLib. A server that requires authentication is supported for the time-stamping (TimestampSettings.UserName, Password, AuthenticationCertificate).

The static class NetworkSettings controls all the HTTP requests of the library:

PropertyDefaultMeaning
ProxynullThe proxy of all the requests: time-stamps, OCSP, CRL, documents loaded from a URL. null uses the default proxy of the platform (section 4.10).
RevocationTimeout20000The time-out, in milliseconds, of an OCSP request, of a CRL download and of the other downloads (not of the time-stamps, which use TimestampSettings.ServerTimeout). It is the same setting as DigitalCertificate.Timeout.
MaxResponseSize52428800 (50 MB)The maximum size of a response (time-stamp, OCSP response, CRL, downloaded document); a larger response is refused with WebException. The CRLs embedded in the signatures have their own limit (MaxCrlSize of the signature classes).
MaxRedirects3The maximum number of HTTP redirects of a request; 0 does not follow them. An HTTPS request is never redirected to HTTP, and the credentials (user and password of the time-stamping server, client certificate) are never sent to another server.
MaxConnectionsPerServer16The simultaneous connections to the same server, for the documents signed in parallel. It applies to .NET Framework; on .NET the connections are not limited.
BlockPrivateAddressesfalseWhen true, the URLs read from the certificates (OCSP responders, CRL distribution points) that point to a local or private address are refused (protection against server-side request forgery through the certificates of untrusted documents). The URLs that the application sets (time-stamping server, PDF URL) are not affected.
AllowLegacyTlstrueAllows TLS 1.0 and 1.1 for old servers; a server that supports TLS 1.2 or 1.3 still negotiates it. With false the requests of the library use only TLS 1.2 and 1.3. On .NET Framework the TLS versions belong to the whole application: the library adds TLS 1.2 (and 1.0, 1.1 when this setting is true) and never removes the versions of the application.

The URLs read from the certificates are used only when they are HTTP or HTTPS URLs (and LDAP for the CRLs).

// Once, when the application starts.
NetworkSettings.RevocationTimeout = 10000;        // 10 seconds for an OCSP request or a CRL download
NetworkSettings.BlockPrivateAddresses = true;     // a public service that verifies documents from unknown sources
NetworkSettings.AllowLegacyTls = false;           // only TLS 1.2 and 1.3

Proxy server

In a network where the Internet is reached through a proxy server that requires authentication, set NetworkSettings.Proxy once, when the application starts. All the HTTP requests of the library then use this proxy: the time-stamps, the OCSP requests, the CRL downloads and the documents loaded from a URL. When it is not set (null, the default), the requests use the default proxy settings of the platform.

// A proxy with a user name and a password.
NetworkSettings.Proxy = new WebProxy("http://proxy.company.com:8080")
{
    Credentials = new NetworkCredential("user", "password", "DOMAIN")
};

// Or: the proxy of the system (the Windows settings) with the Windows credentials of the current user.
IWebProxy systemProxy = WebRequest.GetSystemWebProxy();
systemProxy.Credentials = CredentialCache.DefaultCredentials;
NetworkSettings.Proxy = systemProxy;
Production services

When a document is signed with the long term validation data, the CRL and the OCSP downloads add time to the first call and they depend on servers that you do not control. The data is cached in memory and reused by the next signatures, except the OCSP responses embedded in a long term signature, which are requested after its time-stamp (section 12.5); RevocationCache.Prefetch downloads it before the first document of a batch. Sign with a time limit (a task with a time-out), handle the exceptions of the time-stamping server and of the validation data and, when the volume is large, use a local time-stamping server.

4.11 Security of the documents that are read

The documents that an application verifies often come from unknown sources. The library reads them with limits, set in the static classes SecurityLimits (namespace SignLib) and XmlSignatureVerificationPolicy (namespace SignLib.Xml). The settings are process-wide.

SettingDefaultMeaning
SecurityLimits.AllowXmlDtdfalseAn XML document (XMLDSig, XAdES, ASiC-E, Office) with a document type declaration (DTD) is refused (XmlException). With true the internal DTD is processed, with a limited entity expansion. External entities and resources are never loaded.
SecurityLimits.MaxZipEntries10000The maximum number of entries of an ASiC-E container or of an Office package.
SecurityLimits.MaxZipEntrySize1 GBThe maximum uncompressed size of an entry.
SecurityLimits.MaxZipTotalSize2 GBThe maximum total uncompressed size of a container or package.
SecurityLimits.MaxCompressionRatio1000The maximum compression ratio of an entry larger than 1 MB (against “zip bombs”).
XmlSignatureVerificationPolicy.RejectSha1falseWith true, the XML signatures (XMLDSig, XAdES, ASiC-E, Office) that use SHA-1 in their signature method or in a reference digest are reported as invalid. SHA-1 is never used for the new XML signatures.

A container or package that exceeds a ZIP limit, or that has the same entry twice, is refused with SecurityLimitException. What is refused by default:

Not refused by default, because they break existing documents or infrastructures: the SHA-1 XML signatures (RejectSha1), the private addresses in the certificates (NetworkSettings.BlockPrivateAddresses) and TLS 1.0/1.1 (NetworkSettings.AllowLegacyTls). A public service that verifies documents from anyone should set them:

// Once, when the application starts.
XmlSignatureVerificationPolicy.RejectSha1 = true;
NetworkSettings.BlockPrivateAddresses = true;
SecurityLimits.MaxZipTotalSize = 200L * 1024 * 1024;     // 200 MB: the largest container that the service accepts

5. Digital certificates

A signature is created with the private key of a certificate. This chapter shows how to get an X509Certificate2 for the signature classes, how to inspect and validate certificates, how the library caches them, and how to create certificates for tests and for internal use. The classes are DigitalCertificate (static methods, no serial number needed) and X509CertificateGenerator.

5.1 What the signature classes need

5.2 Loading a certificate

From a PFX (PKCS#12) file

DigitalCertificate.LoadCertificate(string file, string password) and LoadCertificate(byte[] content, string password) load the certificate with its private key. On .NET the library asks the platform to keep the private key in memory (an ephemeral key set), so that it is not written to the disk; on .NET Framework the key is kept in a temporary key container that is deleted when the certificate is disposed.

X509Certificate2 fromFile  = DigitalCertificate.LoadCertificate("cert.pfx", "123456");
X509Certificate2 fromBytes = DigitalCertificate.LoadCertificate(File.ReadAllBytes("cert.pfx"), "123456");

Console.WriteLine(fromFile.Subject + ", private key: " + fromFile.HasPrivateKey);

// Dispose the certificate when you do not need it any more (it releases the private key).
fromFile.Dispose();
fromBytes.Dispose();

A wrong password, or a file that is not a PFX file, throws CryptographicException; a missing file throws FileNotFoundException. The same PFX data with the same password returns the same certificate object while it is not disposed, so loading the PFX file for every document does not import the key again (section 5.5).

The certificates of the chain

The library builds the certificate chain of the signing certificate (the issuer up to the root) to embed the certificates in the signature and, for the long term levels, to request the OCSP responses (an OCSP request needs the certificate of the issuer) and the CRLs of the CA certificates. The chain is built by the certificate chain engine of the platform (X509Chain), from:

A PFX file exported with its whole chain is therefore enough, even for an internal PKI. A certificate that does not come from LoadCertificate (a certificate of the Windows store, of a smart card, or an X509Certificate2 that you create yourself from a PFX file) uses only the stores and the caIssuers address. When the CA certificates are not available in one of these ways (an internal PKI, a server without Internet access), install them in the store of intermediate certification authorities of the account that signs, once:

// The CA certificates of an internal PKI, in the "Intermediate Certification Authorities" store of the current user.
using (X509Store caStore = new X509Store(StoreName.CertificateAuthority, StoreLocation.CurrentUser))
{
    caStore.Open(OpenFlags.ReadWrite);
    caStore.Add(new X509Certificate2("Issuing CA.cer"));
}

The root certificate belongs to the Trusted Root Certification Authorities store (section 5.7). The chains are cached in memory for CertificateCache.MaxAge (one hour by default): a certificate installed while the application runs is used at the latest after this time, or at once after CertificateCache.Clear() (section 5.5).

Without the certificate of the issuer the chain has only the signing certificate. A signature of a level without validation data is created with it; a B-LT or B-LTA signature is refused with ValidationDataException (“the certificate of its issuer was not found”, section 12.4). For the validation of a certificate, the CA certificates can also be given to CertificateValidator (CertificateValidationSettings.IntermediateCertificates, section 5.4).

From the Windows certificate store

The certificates of the current user (or of the local computer) are available to the library, together with the certificates that a smart card or a USB token makes available through its Windows driver (the “minidriver”). The overloads of LoadCertificate either show a selection window or find the certificate by code:

CallResult
LoadCertificate()The Windows selection window with all the certificates of the current user; returns the selected certificate, or null when the user cancels.
LoadCertificate(string subject)The window, with the certificates whose subject contains the text.
LoadCertificate(bool validOnly, string issuerName, string title, string description)The window, with the certificates of an issuer. validOnly keeps only the certificates that are in their validity period. Overloads with fromLocalMachine use the computer store; overloads with smartCardPin set the PIN so that the PIN window does not appear.
LoadCertificate(bool validOnly, DigitalCertificateSearchCriteria criterion, string value)No window: the first certificate that matches. The criteria: a field of the subject (CommonNameCN, OrganizationO, OrganizationUnitOU, EmailE, LocalityL, CountryC, StateS, TitleT), Thumbprint or SerialNumber.
// With a window: the user selects the certificate.
X509Certificate2 selected = DigitalCertificate.LoadCertificate(false, string.Empty, "Select Certificate", "Select the certificate for the digital signature");

// Without a window (services, batch programs): by thumbprint, by serial number or by a field of the subject.
X509Certificate2 byThumbprint = DigitalCertificate.LoadCertificate(true, DigitalCertificateSearchCriteria.Thumbprint, "FAC4D3EF766A59BB068DD90877267EBC56B4232A");
X509Certificate2 byName       = DigitalCertificate.LoadCertificate(true, DigitalCertificateSearchCriteria.CommonNameCN, "John Smith");

// The certificates of the local computer (a service account has no user store).
X509Certificate2 machineCert  = DigitalCertificate.LoadCertificate(true, DigitalCertificateSearchCriteria.Thumbprint, "FAC4D3EF766A59BB068DD90877267EBC56B4232A", true);

if (byThumbprint == null)
    throw new InvalidOperationException("The certificate was not found in the store.");
Windows only, and no window in a service

The store overloads work on Windows. The selection window cannot be shown by a service or by a web application: use the criteria without a window, and set the PIN of a smart card from code. The thumbprint is displayed by the Windows certificate viewer (Details > Thumbprint) and by X509Certificate2.Thumbprint.

A certificate on a smart card or on a USB token

A token whose certificate is in the Windows store is used like any other certificate of the store. The driver of the token asks for the PIN in a window the first time the key is used. To avoid the window, give the PIN to the library:

X509Certificate2 tokenCertificate = DigitalCertificate.LoadCertificate(true, DigitalCertificateSearchCriteria.Thumbprint, "FAC4D3EF766A59BB068DD90877267EBC56B4232A");
string pin = Environment.GetEnvironmentVariable("TOKEN_PIN");     // read the PIN from a protected source

// The PIN is used for the next signing operation of this thread, then the library forgets it.
DigitalCertificate.SmartCardPin = pin;

PdfSignature pdfSignature = new PdfSignature(LibrarySerialNumber);
pdfSignature.LoadPdfDocument("source.pdf");
pdfSignature.DigitalSignatureCertificate = tokenCertificate;

byte[] signedPdf = pdfSignature.ApplyDigitalSignature();

5.3 Reading the certificate

The X509Certificate2 class has the common properties (Subject, Issuer, NotBefore, NotAfter, Thumbprint, SerialNumber). DigitalCertificate adds the checks that the .NET class does not have:

// The key usages: null when the certificate has no key usage extension.
List<CertificateKeyUsage> usages = DigitalCertificate.GetKeyUsage(signingCertificate);
bool canSignDocuments = usages == null || usages.Contains(CertificateKeyUsage.DigitalSignature) || usages.Contains(CertificateKeyUsage.NonRepudiation);

// A certificate that declares itself qualified (the QcCompliance statement, ETSI EN 319 412-5).
// The qualified status itself is given by the EU trusted lists, not by this extension.
bool declaresQualified = DigitalCertificate.IsQualifiedCertificate(signingCertificate);

// All the qualified statements (null when the certificate has no qcStatements extension), see the eIDAS chapter.
QualifiedCertificateInfo qualified = DigitalCertificate.GetQualifiedCertificateInfo(signingCertificate);

// The chain of the certificate, built with the standard .NET class (for a validation, use CertificateValidator).
X509Chain chain = new X509Chain();
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
bool chainBuilt = chain.Build(signingCertificate);

foreach (X509ChainElement element in chain.ChainElements)
    Console.WriteLine(element.Certificate.Subject);

5.4 Validating a certificate

CertificateValidator.Validate (namespace SignLib.Certificates) answers the question that the verification of a signature does not: can the certificate be trusted? It checks, at a given time:

OverloadValidation time and data
Validate(X509Certificate2 certificate)Now, with the default settings.
Validate(X509Certificate2 certificate, CertificateValidationSettings settings)Now.
Validate(X509Certificate2 certificate, DateTime validationTime, CertificateValidationSettings settings)The given time (a time of kind Unspecified is taken as UTC). For a signature, the time of its time-stamp.
Validate(PdfSignatureInfo signature, CertificateValidationSettings settings)
Validate(CadesSignatureInfo signature, CertificateValidationSettings settings)
Validate(XadesSignatureInfo signature, CertificateValidationSettings settings)
The certificate of the signature, at the time of its time-stamp, or now when it has none. The validation data embedded in the signature (the certificates and the OCSP responses and CRLs of a B-LT signature) is used after the data of the settings and before the online sources. ArgumentException when the signature has no certificate (a document time-stamp). For the Office signatures use the overload with the certificate and the time.

The settings (CertificateValidationSettings, null for the defaults):

PropertyDefaultMeaning
UseWindowsTrustedRootstrueThe trusted root certification authorities of Windows are trusted. Set it to false to trust only TrustedRoots (the same result on every computer).
TrustedRootsemptyThe certificates that the application trusts (usually roots; a CA certificate can also be trusted directly).
IntermediateCertificatesemptyCA certificates that help to build the chain when they are not in the certificate stores.
RevocationCheckOcspThenCrlRevocationCheckMode: None, Ocsp, Crl, or OcspThenCrl (the CRL when OCSP gives no status).
CheckRevocationOfCaCertificatestrueThe CA certificates of the chain are checked too, not only the certificate. The trusted root is never checked.
UseOnlineRevocationtrueOCSP responses and CRLs are downloaded from the addresses of the certificates. With false, only OcspResponses, Crls and the data embedded in the signature are used (an offline validation).
OcspResponses, CrlsemptyOCSP responses (DER OCSPResponse or BasicOCSPResponse) and CRLs (DER or PEM) known by the application, used before the online checks.

The result (CertificateValidationResult):

CertificateValidationSettings settings = new CertificateValidationSettings();
settings.TrustedRoots.Add(new X509Certificate2("Root CA.cer"));      // your own root (optional)
// settings.UseWindowsTrustedRoots = false;                         // trust only TrustedRoots

// A certificate, now: for example before signing.
CertificateValidationResult now = CertificateValidator.Validate(signingCertificate, settings);
if (!now.IsTrusted)
    Console.WriteLine(now.Status + ": " + string.Join("; ", now.Problems));

// The certificates of the signatures of a PDF document, at the time of their time-stamps.
PdfSignature verifier = new PdfSignature(LibrarySerialNumber);
verifier.LoadPdfDocument("contract[signed].pdf");

foreach (PdfSignatureInfo info in verifier.DocumentProperties.DigitalSignatures)
{
    if (info.SignatureType == SignatureType.TimestampSignature)
        continue;   // a document time-stamp has no signing certificate

    CertificateValidationResult result = CertificateValidator.Validate(info, settings);
    Console.WriteLine(info.SignatureName + ": intact " + info.SignatureIsValid + ", certificate " + result.Status);

    foreach (KeyValuePair<string, RevocationDataSource> source in result.RevocationSources)
        Console.WriteLine("  " + source.Key + ": revocation status from " + source.Value);
}

A quick check of one certificate

DigitalCertificate.VerifyDigitalCertificate(certificate, type) checks one certificate, without its chain and without a trust decision, and returns a CertificateStatus. It returns Expired when the certificate is not in its validity period (for every type); otherwise:

VerificationTypeWhat it checks
LocalTimeOnly the validity period, with the clock of the computer. No network. Valid.
OCSPAsks the OCSP responder written in the certificate. Valid, Revoked, Unknown (no answer that can be trusted, or the issuer certificate is not found) or NotPresent (no OCSP responder).
CRLDownloads the HTTP CRL of the certificate, verifies it with the key of the issuer and looks for the certificate. NotPresent when the certificate has no CRL.
LDAPThe same, with the LDAP address of the CRL (Windows).
CertificateStatus ocsp = DigitalCertificate.VerifyDigitalCertificate(signingCertificate, VerificationType.OCSP);

if (ocsp == CertificateStatus.Revoked)
{
    // The date of the revocation is read from the CRL of the certificate.
    DateTime revokedOn = DigitalCertificate.GetCertificateRevocationDate(signingCertificate);
    Console.WriteLine("Revoked on " + revokedOn);
}
else if (ocsp == CertificateStatus.NotPresent)
{
    // The certificate has no OCSP responder: try the CRL.
    CertificateStatus crl = DigitalCertificate.VerifyDigitalCertificate(signingCertificate, VerificationType.CRL);
    Console.WriteLine("CRL: " + crl);
}

Unknown is not Valid: decide, for your application, if an unknown status blocks the operation. The downloads use NetworkSettings.RevocationTimeout (section 4.10).

5.5 The certificate cache

The static class CertificateCache (namespace SignLib.Certificates) keeps in memory the certificate data used when signing, so that the documents signed one after another, or in parallel, with the same certificate do not repeat the same work. It is shared by all the signature classes of the process and it is active by default. It keeps:

The PIN of a smart card is never kept. The external signature providers and the certificates selected by the user in the Windows window are not cached. Nothing is written to the disk.

MemberDefaultMeaning
EnabledtrueThe cache is used. Setting it to false also clears it.
MaxAge1 hourThe time an entry is kept from its creation. A chain changed in the certificate stores (for example a new intermediate certificate) is seen at most after this time.
KeepSmartCardKeystrueThe private keys of the smart cards and tokens stay open between the signatures of the same thread, so the PIN is entered once. The cards that require the PIN for every signature (“PIN always”, usual for qualified signature cards) still ask for it. Setting it to false clears the cache.
Clear()Removes all the entries and disposes the cached private keys. The certificates loaded from PFX files are not disposed (the application may still use them).
StatisticsA CertificateCacheStatistics with the number of certificate chains built (ChainBuilds), private keys opened (PrivateKeyOpens) and PFX files loaded (PfxLoads) since the process started: the cache misses, for diagnostics.
// After a change of the certificate stores (a new CA certificate), or when a smart card is replaced.
CertificateCache.Clear();

CertificateCacheStatistics statistics = CertificateCache.Statistics;
Console.WriteLine("Chains built: " + statistics.ChainBuilds + ", keys opened: " + statistics.PrivateKeyOpens + ", PFX loaded: " + statistics.PfxLoads);

The revocation data (OCSP responses and CRLs) has its own cache, RevocationCache (section 12.5).

5.6 Creating certificates

X509CertificateGenerator creates X.509 certificates with RSA or ECDSA keys, in memory, and returns them as PFX (PKCS#12) bytes protected by a password. Use it for tests, for internal use, for the signing of your own documents, and in a small internal certification authority. The certificates are not trusted by the other computers until the root certificate is installed on them. A certificate for the legal signature of documents is issued by a certification authority, after the identification of the person.

The generator needs the serial number of the library. The certificates created by the demo version are valid for 30 days at most (section 2.4).

A self-signed certificate

X509CertificateGenerator generator = new X509CertificateGenerator(LibrarySerialNumber);

generator.ValidFrom = DateTime.Now;
generator.ValidTo = DateTime.Now.AddYears(2);
generator.KeySize = KeySize.KeySize2048Bit;
generator.SignatureAlgorithm = SignatureAlgorithm.SHA256WithRSA;

// The subject as one string, or attribute by attribute with AddToSubject(SubjectType.CN, "...").
generator.Subject = "CN=John Smith, O=Example Ltd, C=RO, E=john@example.com";

// What the certificate can be used for.
generator.Extensions.AddKeyUsage(CertificateKeyUsage.DigitalSignature);
generator.Extensions.AddKeyUsage(CertificateKeyUsage.NonRepudiation);
generator.Extensions.AddEnhancedKeyUsage(CertificateEnhancedKeyUsage.DocumentSigning);

// The PFX file: the certificate and the private key, protected by the password.
byte[] pfx = generator.GenerateCertificate("123456", false);

File.WriteAllBytes("john.pfx", pfx);

// The public part, to give to the people who verify the signatures.
X509Certificate2 certificate = new X509Certificate2(pfx, "123456");
File.WriteAllBytes("john.cer", certificate.RawData);

The second parameter of GenerateCertificate(password, isRootCertificate) is false for an end-entity certificate and true for a CA certificate. When no root certificate is loaded, the certificate is signed with its own key (self-signed).

Settings of the generator

Property / methodMeaning and default
Subject, AddToSubjectThe subject. AddToSubject(SubjectType, value) builds it attribute by attribute (CN, O, OU, C, E, SERIALNUMBER, GIVENNAME...). When Subject is set, it replaces the attributes. One of them is required.
ValidFrom, ValidToThe validity, in local time. Defaults: now, and one year later (30 days at most on the demo version).
KeyAlgorithm, KeySize, EllipticCurveRSA (default) or ECDSA. The RSA size is KeySize2048Bit by default (use KeySize4096Bit for CA certificates; the 512 and 1024 bit sizes are obsolete). The ECDSA curves: NistP256 (the default), NistP384, NistP521, BrainpoolP256r1, BrainpoolP384r1, BrainpoolP512r1.
SignatureAlgorithmThe hash of the signature of the certificate (SHA-1 not recommended; SHA-256, SHA-384, SHA-512). The signature is RSA or ECDSA by the key of the issuer.
SerialNumberThe serial number of the certificate; a random 128-bit number when it is not set.
FriendlyNameThe name in the PFX file; a unique name when it is empty.
SubjectAlternativeNames, AddSubjectAlternativeNameThe alternative names (DNS, IP address, e-mail, URI). The type is detected from the value, or given explicitly with SubjectAlternativeNameType.
ExtensionsKey usages, enhanced key usages, CRL addresses, OCSP, CA issuers, policies, QC statements, path length (section 5.6).
LoadRootCertificate(byte[] pfx, string password)The issuer: the next certificates are signed with this CA certificate.

An ECDSA certificate

X509CertificateGenerator generator = new X509CertificateGenerator(LibrarySerialNumber);

generator.KeyAlgorithm = KeyAlgorithm.ECDSA;
generator.EllipticCurve = EllipticCurve.NistP384;
generator.SignatureAlgorithm = SignatureAlgorithm.SHA384WithECDSA;     // the hash; the algorithm follows the key of the issuer
generator.Subject = "CN=ECDSA signer, O=Example Ltd";
generator.Extensions.AddKeyUsage(CertificateKeyUsage.DigitalSignature);

byte[] pfx = generator.GenerateCertificate("123456", false);

The key usages of an ECDSA key are checked against RFC 5480: KeyEncipherment and DataEncipherment are not allowed for these keys.

A root certificate and a certificate that it issues

// 1. The root (CA) certificate.
X509CertificateGenerator root = new X509CertificateGenerator(LibrarySerialNumber);
root.ValidTo = DateTime.Now.AddYears(10);
root.KeySize = KeySize.KeySize4096Bit;
root.Subject = "CN=Example Root CA, O=Example Ltd";
root.Extensions.AddKeyUsage(CertificateKeyUsage.CertificateSigning);
root.Extensions.AddKeyUsage(CertificateKeyUsage.CRLSigning);
root.Extensions.PathLengthConstraint = 0;      // the CA issues only end-entity certificates
byte[] rootPfx = root.GenerateCertificate("rootPassword", true);

// 2. An end-entity certificate issued by the root.
X509CertificateGenerator user = new X509CertificateGenerator(LibrarySerialNumber);
user.LoadRootCertificate(rootPfx, "rootPassword");
user.ValidTo = DateTime.Now.AddYears(2);
user.Subject = "CN=Mary Jones, O=Example Ltd";
user.Extensions.AddKeyUsage(CertificateKeyUsage.DigitalSignature);
user.Extensions.AddKeyUsage(CertificateKeyUsage.NonRepudiation);
user.Extensions.KeyUsageIsCritical = true;
byte[] userPfx = user.GenerateCertificate("userPassword", false);

// The PFX of the user also contains the root certificate: loaded with LoadCertificate, it completes the chain of the
// signatures created with the user certificate.
X509Certificate2 userCertificate = DigitalCertificate.LoadCertificate(userPfx, "userPassword");

To install the root certificate on the computers that must trust the certificates (the Windows store Trusted Root Certification Authorities), distribute its public part (rootCertificate.RawData, a .cer file), never the PFX.

Extensions: revocation addresses, policies, qualified statements

The validators use the addresses in the certificate to check its revocation. A certificate that you issue for a test of the long term validation features needs them (and CRL and OCSP servers that answer at these addresses):

X509CertificateGenerator generator = new X509CertificateGenerator(LibrarySerialNumber);
generator.Subject = "CN=Test signer, O=Example Ltd";
generator.Extensions.AddKeyUsage(CertificateKeyUsage.DigitalSignature);

generator.Extensions.AddCrlDistributionPoint("http://crl.example.com/ca.crl");   // where the CRL is published
generator.Extensions.AddOcspUrl("http://ocsp.example.com");                     // the OCSP responder
generator.Extensions.AddCaIssuersUrl("http://www.example.com/ca.cer");          // where the certificate of the issuer is

// A certificate policy, with optional qualifiers (the address of the CPS and a user notice).
generator.Extensions.AddCertificatePolicy("1.2.3.4.5", "https://www.example.com/cps", "Certificate for tests");

generator.SubjectAlternativeNames = "john@example.com";

For the tests of an eIDAS application, the generator can write the QCStatements extension (ETSI EN 319 412-5), so that the certificate declares itself as qualified, with the private key in a qualified device. Such a certificate is not a qualified certificate (it is not issued by a qualified trust service provider): it exists to test the code that reads these statements (DigitalCertificate.IsQualifiedCertificate, DigitalCertificate.GetQualifiedCertificateInfo, section 14.4).

X509CertificateGenerator generator = new X509CertificateGenerator(LibrarySerialNumber);
generator.AddToSubject(SubjectType.CN, "Test Qualified Signer");
generator.AddToSubject(SubjectType.SERIALNUMBER, "PNORO-1234567890123");
generator.Extensions.AddKeyUsage(CertificateKeyUsage.NonRepudiation);

generator.Extensions.QcStatements = new QualifiedCertificateStatements
{
    QcCompliance = true,                                     // an EU qualified certificate
    QcSscd = true,                                           // the key is in a qualified signature creation device
    QcType = QualifiedCertificateType.ESign,                 // a certificate for electronic signatures
    SemanticsIdentifier = QcSemanticsIdentifier.NaturalPerson,
    RetentionPeriod = 10                                     // years
};
generator.Extensions.QcStatements.AddPdsLocation("https://www.example.com/pds_en.pdf", "en");
generator.Extensions.AddCertificatePolicy("0.4.0.194112.1.2");   // QCP-n-qscd

byte[] pfx = generator.GenerateCertificate("123456", false);

A certificate for a certificate signing request (CSR)

A small internal certification authority issues certificates for the keys that the users generate themselves: the user sends a PKCS#10 request (PEM text) and gets the certificate, without the private key leaving the user.

X509CertificateGenerator ca = new X509CertificateGenerator(LibrarySerialNumber);
ca.LoadRootCertificate(File.ReadAllBytes("root.pfx"), "rootPassword");
ca.ValidTo = DateTime.Now.AddYears(1);
ca.Extensions.AddKeyUsage(CertificateKeyUsage.DigitalSignature);
ca.Extensions.AddKeyUsage(CertificateKeyUsage.NonRepudiation);

string csrPem = File.ReadAllText("request.csr");       // -----BEGIN CERTIFICATE REQUEST----- ...
byte[] certificateDer = ca.GenerateCertificateFromCSR(csrPem);

File.WriteAllBytes("issued.cer", certificateDer);

5.7 Installing certificates in the Windows store

The certificates in the Windows store are used by the programs of the computer, and they are the way to make a certificate trusted (a root certificate) or available to a service (a signing certificate). The Windows tools are certmgr.msc (the current user) and certlm.msc (the local computer); a PFX file is installed by double-clicking it, or with the PowerShell cmdlet Import-PfxCertificate. From code, use the X509Store class of .NET:

// A PFX certificate (with its private key) in the Personal store of the current user.
X509Certificate2 signingCert = new X509Certificate2("cert.pfx", "123456", X509KeyStorageFlags.PersistKeySet);

using (X509Store personal = new X509Store(StoreName.My, StoreLocation.CurrentUser))
{
    personal.Open(OpenFlags.ReadWrite);
    personal.Add(signingCert);
}

// The same for the Local Computer store (needs administrator rights): a service account can then use the certificate.
using (X509Store machine = new X509Store(StoreName.My, StoreLocation.LocalMachine))
{
    machine.Open(OpenFlags.ReadWrite);
    machine.Add(signingCert);
}

// A root certificate (the public part only) in the Trusted Root Certification Authorities store.
// For the current user Windows asks the user to confirm; for the local computer it needs administrator rights.
using (X509Store roots = new X509Store(StoreName.Root, StoreLocation.CurrentUser))
{
    roots.Open(OpenFlags.ReadWrite);
    roots.Add(new X509Certificate2("root.cer"));
}
Protect the keys
  • The password of a PFX file and the PIN of a token are secrets: do not put them in the source code of an application that you distribute.
  • The PFX of a root certificate is the key of your whole internal PKI. Keep it offline, or in an HSM, and use it only to issue certificates.
  • A self-signed certificate proves nothing to a recipient who does not already trust it.

6. PDF signatures

The class PdfSignature signs PDF documents. It creates the signatures that Adobe Acrobat and the other PDF readers show in the signature panel: the classic PKCS#7 signature (adbe.pkcs7.detached) and the PAdES signatures of ETSI EN 319 142-1 (ETSI.CAdES.detached), with a time-stamp, with the validation data for the long term (PAdES-B-LT) and with a document time-stamp for archiving (PAdES-B-LTA). The same class reads the signatures of a document and verifies them. Related classes: PdfEncrypt (encryption), PdfMerge and PdfInsertObject (merging and adding text and images).

6.1 How a PDF signature works

A PDF signature is a signature field in the document. The library does not rewrite the document: it appends a new revision to the end of the file (an incremental update) that contains the signature field, its appearance and the signature value. The bytes of the document that existed before are not changed, so the signatures that were already in the document remain valid (PdfSignature.AppendSignature is true by default). The signature value covers the whole file, except the space that holds the signature itself (the /ByteRange).

Original documentpages, fonts, form fields Revision 1: signature 1field + appearance + CMS signature Revision 2: signature 2appended; signature 1 stays valid signed by signature 1 signed by signature 2: the whole file up to its own value
Every signature covers the file up to the end of its revision. A change after the last signature (a changed page, an added file end) is not covered, and the PDF readers report it.

The steps of the code are always the same: LoadPdfDocument → set the certificate and the options → ApplyDigitalSignature() → the signed document as byte[] (or ApplyDigitalSignature(Stream), which writes it to a stream: section 6.12).

PdfSignature pdfSignature = new PdfSignature(LibrarySerialNumber);

pdfSignature.LoadPdfDocument("source.pdf");               // or a byte[], a Uri or a Stream
pdfSignature.DigitalSignatureCertificate = signingCertificate;

byte[] signedPdf = pdfSignature.ApplyDigitalSignature();
File.WriteAllBytes("source[signed].pdf", signedPdf);

6.2 Loading the document

PdfSignature pdfSignature = new PdfSignature(LibrarySerialNumber);

// The password of an encrypted document: before the document is loaded.
pdfSignature.DocumentProperties.Password = "document password";
pdfSignature.LoadPdfDocument("encrypted.pdf");

PdfDocumentProperties properties = pdfSignature.DocumentProperties;
Console.WriteLine("Pages: " + properties.NumberOfPages + ", size: " + properties.FileSize + " bytes");
Console.WriteLine("Signatures: " + properties.DigitalSignatures.Count + ", certification: " + properties.CertificationLevel);

System.Drawing.Point firstPage = properties.DocumentPageSize(1);     // X = width, Y = height, in points
Console.WriteLine("Page 1: " + firstPage.X + " x " + firstPage.Y);

A document can be loaded from a web address and checked before it is signed, for example to sign only the documents that have no signature yet:

PdfSignature pdfSignature = new PdfSignature(LibrarySerialNumber);
pdfSignature.LoadPdfDocument(new Uri("https://www.example.com/documents/contract.pdf"));      // an HTTP download

if (pdfSignature.DocumentProperties.DigitalSignatures.Count == 0)
{
    pdfSignature.DigitalSignatureCertificate = signingCertificate;
    File.WriteAllBytes("contract[signed].pdf", pdfSignature.ApplyDigitalSignature());
}
else
{
    Console.WriteLine("The document is already signed " + pdfSignature.DocumentProperties.DigitalSignatures.Count + " time(s).");
}

6.3 Signature formats

The property SignatureStandard (PdfSignatureStandard) selects the format. The default is the classic PKCS#7:

ValueWhat is createdUse it when
DefaultPKCS#7 detached (adbe.pkcs7.detached).The signature must be recognized by every PDF reader, also the old ones. The format of most of the signatures in use.
PadesPAdES baseline B-B (ETSI.CAdES.detached, the signing certificate is a signed attribute).A regulation or a validator asks for PAdES (the eIDAS signatures). Recognized by Adobe Reader X and later. Use a hash of the SHA-2 family with PAdES.
PadesLTPAdES B-LT: the time-stamped signature, plus the certificates and the revocation data (CRL, OCSP) of the signer and of the time-stamping authority in the document security store (/DSS).The signature must be validated later, after the certificate expires or the servers of the certification authority are gone. Needs the network and a time-stamping server (TimeStamping.ServerUrl) when the signature is created. (→ section 12)
PadesLTAPAdES B-LTA: PAdES-LT followed by a document time-stamp that protects the document and its validation data.Archiving for many years. Needs a time-stamping server (TimeStamping.ServerUrl). The time-stamp can be renewed (section 12.6).

A time-stamp on the signature (B-T) is added with any of the formats when TimeStamping.ServerUrl is set (section 6.8).

The hash algorithm is HashAlgorithm (SignLib.HashAlgorithm: SHA256 by default, SHA384, SHA512, SHA1 for old systems). The algorithm of the signature follows the key of the certificate: RSA (PKCS#1 v1.5) or ECDSA. The verification accepts more algorithms than the signing (section 6.11).

PdfSignature pdfSignature = new PdfSignature(LibrarySerialNumber);
pdfSignature.LoadPdfDocument("source.pdf");
pdfSignature.DigitalSignatureCertificate = signingCertificate;

pdfSignature.SignatureStandard = PdfSignatureStandard.Pades;
pdfSignature.HashAlgorithm = SignLib.HashAlgorithm.SHA384;

File.WriteAllBytes("source[pades].pdf", pdfSignature.ApplyDigitalSignature());
Which format?

For a signature that a person opens in Adobe Reader and that has no regulatory requirement, Default (PKCS#7) is recognized everywhere. For signatures in the European Union, where a qualified or an advanced signature is required and validated with the EU DSS validator, use PAdES. Old PDF readers and some verification programs do not recognize PAdES. If Adobe does not show the signature as valid, see “Signature validity is unknown” in Adobe: causes and solutions.

6.4 Visible and invisible signatures, position

A signature is visible by default: it has a rectangle on a page with the name of the signer, the date, the reason and the location. To sign without a visible appearance set VisibleSignature = false: the signature is only in the signature panel of the PDF reader.

Position by the corner of the page

SignaturePosition places a rectangle of 100 × 50 points at 50 points from the edges of the visible area of the page (its crop box, with the rotation of the page applied); the Middle positions are centered horizontally. The default is TopRight; the other values are TopMiddle, TopLeft, BottomRight, BottomMiddle and BottomLeft.

Position by rectangle

SignatureAdvancedPosition (a System.Drawing.Rectangle, write-only) sets the rectangle. The coordinates are in points and the origin is the bottom left corner of the page: X and Y are the position of the bottom left corner of the rectangle, Width and Height its size. It replaces SignaturePosition.

signatureWidth × Height X Y (0, 0): bottom left A4 portrait: 595 × 842 points US Letter: 612 × 792 points Rectangle(10, 10, 400, 150):400 × 150 points, 10 pointsfrom the left and the bottom edge.
The origin of the coordinates is the bottom left corner of the page, the unit is the point (1/72 inch). The rotation of a page is applied by the library: use DocumentPageSize(page) to know the size that you see.
PdfSignature pdfSignature = new PdfSignature(LibrarySerialNumber);
pdfSignature.LoadPdfDocument("source.pdf");
pdfSignature.DigitalSignatureCertificate = signingCertificate;

// 400 x 150 points, 10 points from the left edge and from the bottom edge of the page.
pdfSignature.SignatureAdvancedPosition = new System.Drawing.Rectangle(10, 10, 400, 150);

File.WriteAllBytes("source[signed].pdf", pdfSignature.ApplyDigitalSignature());

The page

PropertyEffect
SignaturePageThe page of the signature, numbered from 1. The default is 1. int.MaxValue means the last page. A page that does not exist throws ArgumentOutOfRangeException.
SignaturePages (List<int>)The appearance of the signature on several pages (a page listed twice gets it once; int.MaxValue is the last page). The rectangle is the same on every page. The signature stays a single signature.
SignatureAppearsOnAllPagestrue: the appearance on every page, once on each page. It has priority over SignaturePages.
// pdfSignature: the PdfSignature object of the previous examples (certificate set, document loaded)
// The appearance on the first page and on the last page.
pdfSignature.SignaturePages = new List<int> { 1, int.MaxValue };

// Or on every page of the document.
pdfSignature.SignatureAppearsOnAllPages = true;

6.5 The appearance of the signature

Text

By default the rectangle shows, on separate lines, the name of the signer (the common name of the certificate), the date and time (yyyy.MM.dd HH:mm), the reason and the location. SignatureText replaces the whole text. SigningReason and SigningLocation are also written in the properties of the signature, where the PDF readers show them (the Reason and the Location of the signature panel).

// pdfSignature: the PdfSignature object of the previous examples (certificate set, document loaded)
pdfSignature.SigningReason = "I approve this document";
pdfSignature.SigningLocation = "Accounting department";

// A custom text (the lines are separated with a new line).
pdfSignature.SignatureText = "Signed by: " + signingCertificate.GetNameInfo(X509NameType.SimpleName, false)
    + Environment.NewLine + "Date: " + DateTime.Now.ToString("dd.MM.yyyy HH:mm");

Font

// pdfSignature: the PdfSignature object of the previous examples (certificate set, document loaded)
// Greek and Cyrillic text, with an embedded TrueType font.
pdfSignature.FontFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "arial.ttf");
pdfSignature.FontSize = 11;
pdfSignature.SignatureText = "Υπογράφηκε ψηφιακά" + Environment.NewLine + "Подписано цифровой подписью";

// A right to left text.
pdfSignature.TextDirection = TextDirection.RightToLeft;

Image

SignatureImage (a byte[] with a JPG, PNG, GIF, BMP or TIFF image) adds a graphic to the signature. SignatureImageType says how it is shown:

ValueAppearance
ImageAndText (default)The image on the left and the text on the right.
ImageAsBackgroundThe image is the background of the text.
ImageWithNoTextOnly the image; the text is not shown (the signer information is still in the signature).
// pdfSignature: the PdfSignature object of the previous examples (certificate set, document loaded)
pdfSignature.SignatureImage = File.ReadAllBytes("signature_image.jpg");
pdfSignature.SignatureImageType = SignatureImageType.ImageAndText;
pdfSignature.SignatureAdvancedPosition = new System.Drawing.Rectangle(10, 10, 400, 150);

Other properties of the appearance and of the signer

PropertyMeaning
OldStyleAdobeSignaturetrue: the old Adobe Acrobat 6 appearance (a large question mark on the signatures that are not trusted, and a check mark on the valid ones). The default is false.
SignerContactInformationThe contact information of the signer, in the signature. By default the e-mail address of the certificate.
SigningApplicationName, SigningApplicationVersionThe name and the version of your application, written in the signature build properties. Adobe Reader shows them in the advanced properties of the signature (“Signature was created using ...”); without them it shows “Not available”. The name has at most 127 bytes in UTF-8, without control characters (ArgumentException otherwise).
// pdfSignature: the PdfSignature object of the previous examples (certificate set, document loaded)
pdfSignature.SigningApplicationName = "Invoice Portal";
pdfSignature.SigningApplicationVersion = "3.2.1";

An invisible signature

// pdfSignature: the PdfSignature object of the previous examples (certificate set, document loaded)
pdfSignature.VisibleSignature = false;      // no rectangle on the page; the signature panel shows it

6.6 Certification signatures

A certification signature is the first signature of a document, made by the author, that says which changes are allowed after it (the DocMDP permission). The property CertifySignature (CertifyMethod) sets it:

ValueAfter the certification signature
NotCertified (default)A normal approval signature.
NoChangesAllowedNo changes. No other signature can be added.
FormFillingFilling the form fields and signing are allowed.
AnnotationsAndFormFillingAnnotations, form filling and signing are allowed.

A document has at most one certification signature and it must be the first. The certification level of a loaded document is DocumentProperties.CertificationLevel. The library refuses, with an InvalidOperationException and before anything is signed, the operations that would break these rules: a certification signature on a document that is already signed or certified, and a new signature on a document certified with NoChangesAllowed.

PdfSignature author = new PdfSignature(LibrarySerialNumber);
author.LoadPdfDocument("source.pdf");
author.DigitalSignatureCertificate = signingCertificate;
author.CertifySignature = CertifyMethod.AnnotationsAndFormFilling;
byte[] certified = author.ApplyDigitalSignature();

// A second signer approves the certified document.
PdfSignature approver = new PdfSignature(LibrarySerialNumber);
approver.LoadPdfDocument(certified);
approver.DigitalSignatureCertificate = signingCertificate;
approver.SignaturePosition = SignaturePosition.BottomLeft;
byte[] approved = approver.ApplyDigitalSignature();

6.7 Several signatures and signature fields

// 1. Prepare: a document with two empty signature fields.
PdfSignature prepare = new PdfSignature(LibrarySerialNumber);
prepare.LoadPdfDocument("source.pdf");
byte[] withField1 = prepare.AddSignatureField("Customer", 1, new System.Drawing.Rectangle(50, 100, 200, 60));

prepare = new PdfSignature(LibrarySerialNumber);
prepare.LoadPdfDocument(withField1);
byte[] withFields = prepare.AddSignatureField("Supplier", 1, new System.Drawing.Rectangle(300, 100, 200, 60));

// 2. Later, every signer signs the field with its name.
PdfSignature customer = new PdfSignature(LibrarySerialNumber);
customer.LoadPdfDocument(withFields);
customer.DigitalSignatureCertificate = signingCertificate;
byte[] signedByCustomer = customer.ApplyDigitalSignature("Customer");

PdfSignature supplier = new PdfSignature(LibrarySerialNumber);
supplier.LoadPdfDocument(signedByCustomer);
supplier.DigitalSignatureCertificate = signingCertificate;
byte[] signedByBoth = supplier.ApplyDigitalSignature("Supplier");

6.8 Time-stamps in PDF documents

A time-stamp proves the time. There are two kinds in a PDF document:

// The signature is time-stamped.
PdfSignature pdfSignature = new PdfSignature(LibrarySerialNumber);
pdfSignature.LoadPdfDocument("source.pdf");
pdfSignature.DigitalSignatureCertificate = signingCertificate;
pdfSignature.TimeStamping.ServerUrl = new Uri("https://ca.signfiles.com/TSAServer.aspx");
File.WriteAllBytes("source[signed-T].pdf", pdfSignature.ApplyDigitalSignature());

// A document time-stamp on the signed document.
PdfSignature stamper = new PdfSignature(LibrarySerialNumber);
stamper.LoadPdfDocument("source[signed-T].pdf");
stamper.TimeStamping.ServerUrl = new Uri("https://ca.signfiles.com/TSAServer.aspx");
File.WriteAllBytes("source[stamped].pdf", stamper.ApplyTimestampSignature());

The settings of the time-stamping server (authentication, policy, hash, time-out) are in section 11. The time-stamp requests use SHA-256 by default.

6.9 PAdES-LT and PAdES-LTA

SignatureStandard = PdfSignatureStandard.PadesLT embeds, in the document security store of the PDF, the certificates and the revocation information of the signer and of the time-stamping authority of the signature time-stamp, which the library downloads when it signs. PdfSignatureStandard.PadesLTA adds the document time-stamp. The property PadesLtvLevel selects the revocation data:

PadesLtvLevelEmbedded revocation data
IncludeOcspOnly (default)The OCSP response of the signing certificate, when available (otherwise its CRL, so that the signature always has revocation data), and the CRLs of the CA certificates. The smallest result.
IncludeCrlAndOcspThe CRLs of the whole chain and the OCSP responses of the signing certificate and of its issuer, when available.
IncludeCrlThe CRLs of the chain, when available.
NoneNo revocation data. Not accepted for PadesLT and PadesLTA (see below).

PadesLtvLevel applies to the Default and Pades signatures too: the revocation data of the signing certificate that can be obtained is written inside the signature (the Adobe revocation attribute). Set PadesLtvLevel = PadesLtvLevel.None for a Default or Pades signature without OCSP and CRL requests. When the revocation data is collected and the signing certificate is revoked, the signature is not created: CertificateRevokedException.

A PAdES-LT or PAdES-LTA signature is created only when it is complete (AllowIncompleteValidationData = false, the default):

With AllowIncompleteValidationData = true the signature is created with the data that could be obtained. With the encryption of section 6.10, PAdES-LT and PAdES-LTA need Encryption.OwnerPassword (InvalidOperationException otherwise) and cannot use CertificateSecurity (NotSupportedException).

PdfSignature pdfSignature = new PdfSignature(LibrarySerialNumber);
pdfSignature.LoadPdfDocument("source.pdf");
pdfSignature.DigitalSignatureCertificate = signingCertificate;

pdfSignature.SignatureStandard = PdfSignatureStandard.PadesLTA;       // signature + validation data + document time-stamp
pdfSignature.PadesLtvLevel = PadesLtvLevel.IncludeCrlAndOcsp;
pdfSignature.TimeStamping.ServerUrl = new Uri("https://ca.signfiles.com/TSAServer.aspx");
pdfSignature.TimeStamping.HashAlgorithm = SignLib.HashAlgorithm.SHA256;

File.WriteAllBytes("source[lta].pdf", pdfSignature.ApplyDigitalSignature());

The certificates of the chain (except the root) must have a CRL or an OCSP responder for the revocation data to exist; a self-signed certificate is a root and needs none.

Renewal. AddArchiveTimestamp() renews a PAdES-LTA document: it adds to the document security store the validation data of all the signatures and document time-stamps (in particular of the time-stamping authority of the last document time-stamp), then a new document time-stamp. The signing certificate is not needed; TimeStamping, PadesLtvLevel and AllowIncompleteValidationData are used. It refuses a document that is not signed (InvalidOperationException) and a document with a signature that is not valid (CryptographicException). AddArchiveTimestamp(Stream) writes the result to a stream (section 6.12).

PdfSignature renewal = new PdfSignature(LibrarySerialNumber);
renewal.LoadPdfDocument("source[lta].pdf");
renewal.TimeStamping.ServerUrl = new Uri("https://ca.signfiles.com/TSAServer.aspx");

File.WriteAllBytes("source[lta-renewed].pdf", renewal.AddArchiveTimestamp());

When to renew (LongTermArchive.GetPdfRenewalDate) and how the long term features work is in section 12 and section 12.6.

6.10 Encryption

Signing and encrypting in one operation

The property PdfSignature.Encryption (PdfEncryptionSettings) encrypts the document while it is signed. The signature is created over the encrypted document, so it stays valid. An encrypted document that is signed again is a problem: the encryption cannot be changed after a signature exists, and a document that is already signed (or certified) cannot be encrypted: it throws CryptographicException. Encrypt first, sign after, or do both together.

PdfSignature pdfSignature = new PdfSignature(LibrarySerialNumber);
pdfSignature.LoadPdfDocument("source.pdf");
pdfSignature.DigitalSignatureCertificate = signingCertificate;

pdfSignature.Encryption.EncryptionMethod = PdfEncryptionMethod.PasswordSecurity;
pdfSignature.Encryption.EncryptionAlgorithm = PdfEncryptionAlgorithm.EnhancedEncryption128BitAES;
pdfSignature.Encryption.UserPassword = "user_passw0rd";        // opens the document
pdfSignature.Encryption.OwnerPassword = "owner_passw0rd";      // all the actions
pdfSignature.Encryption.DocumentRestrictions = PdfDocumentRestrictions.AllowPrinting;

File.WriteAllBytes("source[signed-encrypted].pdf", pdfSignature.ApplyDigitalSignature());

Encrypting a document: PdfEncrypt

PdfEncrypt encrypts a document (without signing it). The settings are the same:

PropertyMeaning
EncryptionMethodPasswordSecurity; CertificateSecurity (the document is opened only with the private key of a certificate); NoEncryption (default).
EncryptionAlgorithmEnhancedEncryption128BitAES (AES-128, recommended); StandardEncryption128BitRC4 (weak) and StandardEncryption40BitRC4 (insecure), only for very old readers. The AES-256 encryption of PDF 2.0 is not supported.
UserPassword, OwnerPasswordThe password to open the document, and the password that allows all the actions.
EncryptionCertificateFor CertificateSecurity: the certificate of the recipient (the public part is enough).
DocumentRestrictionsThe allowed actions, combined: AllowPrinting, AllowContentCopying, AllowFillingOfFormFields, AllowContentCopyingForAccessibility, AllowDocumentAssembly; AllowNone.
LoadedDocumentPasswordThe password of the document that is already encrypted and that you encrypt again.
AllowSignatureInvalidationfalse (default): a signed document is refused with InvalidOperationException. true: it is encrypted, and its signatures become invalid.

The passwords are written in PDFDocEncoding, the encoding of the PDF encryption: a password with a character that it cannot represent (for example “ș” or “ț”) throws ArgumentException. Use letters, digits and the characters of the Latin-1 alphabet.

// Passwords.
PdfEncrypt byPassword = new PdfEncrypt();
byPassword.LoadPdfDocument("source.pdf");
byPassword.EncryptionMethod = PdfEncryptionMethod.PasswordSecurity;
byPassword.EncryptionAlgorithm = PdfEncryptionAlgorithm.EnhancedEncryption128BitAES;
byPassword.UserPassword = "user_passw0rd";
byPassword.OwnerPassword = "owner_passw0rd";
byPassword.DocumentRestrictions = PdfDocumentRestrictions.AllowPrinting | PdfDocumentRestrictions.AllowFillingOfFormFields;
File.WriteAllBytes("source[encrypted].pdf", byPassword.EncryptPDFFile());

// A certificate: only the owner of its private key opens the document, without a password.
PdfEncrypt byCertificate = new PdfEncrypt();
byCertificate.LoadPdfDocument("source.pdf");
byCertificate.EncryptionMethod = PdfEncryptionMethod.CertificateSecurity;
byCertificate.EncryptionCertificate = new X509Certificate2(signingCertificate.RawData);   // the public part
File.WriteAllBytes("source[encrypted-cert].pdf", byCertificate.EncryptPDFFile());
Encrypting a signed document

PdfEncrypt rewrites the file, which invalidates the signatures: it refuses a signed document unless AllowSignatureInvalidation is true. Sign and encrypt in one operation with PdfSignature.Encryption when the result must be an encrypted and signed document.

6.11 Reading and verifying the signatures

After LoadPdfDocument, DocumentProperties.DigitalSignatures lists the signatures and the document time-stamps, sorted by signing time. They are read and verified when the list is used the first time. Every item is a PdfSignatureInfo:

PropertyMeaning
SignatureTypeDigitalSignature, or TimestampSignature for a document time-stamp.
SignatureNameThe name of the signature field.
SignatureIsValidThe integrity of the signature (not the trust of the certificate, section 4.5). The byte range must be well formed (two ranges [0 a b c], the gap being exactly the /Contents value), and the signing certificate must be the one named by the signing-certificate attribute, when the signature has it. For a document time-stamp, the message imprint must be the hash of the byte range.
CoversWholeDocumenttrue when the signature covers the file up to its end. false when the file was changed after the signature: by a later signature, a document security store, a document time-stamp, or any other incremental update. The signature can be valid; the later changes are not covered by it.
SignatureAlgorithmNotSupportedtrue when the signature algorithm or the digest algorithm of the signature is not known to the library: the signature could not be verified. SignatureIsValid is then false, but the signature was not found altered.
Level (SignatureLevel)The effective level, determined from what the signature contains: B, T, LT, LTA; None for a signature that is not an AdES signature (a PKCS#7 signature without the signing-certificate attribute, a document time-stamp) or that is not valid (section 12.4).
ValidationDataComplete, MissingValidationDataWhether the document contains an OCSP response or a CRL for every certificate (except the root) of the chains of the signer and of the time-stamping authority of the signature time-stamp, valid at the time of the time-stamp; otherwise the certificates without data (MissingValidationData: subject, thumbprint, IsTimestampAuthority, reason).
SignatureCertificateThe signing certificate (for a document time-stamp: the certificate of the time-stamping authority).
SignatureTime, SignatureIsTimestamped, TimestampInfoThe signing time (the time of the time-stamp when there is one) and the time-stamp of the signature (TimestampInfo, section 11.3). A time-stamp counts only when its message imprint is the hash of the signature value and its signature is valid: a time-stamp copied from another signature leaves SignatureIsTimestamped false and has TimestampInfo.IsTimestampAltered true.
HashAlgorithm, DigestAlgorithm, SignatureAlgorithmThe hash (SHA256), the signature algorithm (SHA256withRSA, SHA256withECDSA) and the algorithm of the key (RSA, DSA, ECC).
SigningReason, SigningLocationThe reason and the location written by the signer.
SignatureBytes, SignatureHashThe encoded PKCS#7 / CMS structure of the signature, and the signature value.

Algorithms. The library signs with RSA (PKCS#1 v1.5) and ECDSA, with SHA-1, SHA-256, SHA-384 or SHA-512. It verifies, in addition, the signatures that other software creates with RSASSA-PSS, with ECDSA and SHA-224 or SHA-3, and with Ed25519. A signature with an algorithm that the library does not know has SignatureIsValid = false and SignatureAlgorithmNotSupported = true: treat it as “not verified”, not as “altered”.

A complete verification of a document answers more than SignatureIsValid. These checks are a good minimum; the first ones are the library, the last ones are your decision:

  1. every signature is intact (SignatureIsValid), or it uses an algorithm that cannot be verified (SignatureAlgorithmNotSupported);
  2. the last revision of the file is covered by a signature: one signature or document time-stamp has CoversWholeDocument true. Bytes added after the last signature are not signed, although the signatures are still intact. In a PAdES-LTA document, the signature itself does not cover the whole file (the document security store and the document time-stamp follow it): the document time-stamp does;
  3. the time-stamps are not altered (TimestampInfo.IsTimestampAltered);
  4. the signing certificate was valid at the signing time (the time of the time-stamp when there is one), its chain ends in a root that the application trusts, and it was not revoked: CertificateValidator.Validate(signature, settings) does these checks at the time of the time-stamp, and it uses the validation data embedded in the document first (section 5.4).
public static class PdfVerifier
{
    // Returns true when the signatures of the document are intact, the last revision of the file is signed, and the
    // certificates of the signers are trusted at the signing time.
    public static bool Verify(Stream pdf, string serialNumber)
    {
        PdfSignature pdfSignature = new PdfSignature(serialNumber);
        pdfSignature.LoadPdfDocument(pdf);                     // the stream stays open until the end of the verification

        List<PdfSignatureInfo> signatures = pdfSignature.DocumentProperties.DigitalSignatures;
        if (signatures.Count == 0)
            return false;

        bool passed = true;

        // 1. The last revision of the file is covered by a signature or by a document time-stamp.
        if (!signatures.Any(s => s.CoversWholeDocument))
        {
            Console.WriteLine("Data was added after the last signature.");
            passed = false;
        }

        foreach (PdfSignatureInfo info in signatures)
        {
            Console.WriteLine(info.SignatureName + " (" + info.SignatureType + ", level " + info.Level + ")");

            // 2. The integrity of the signature.
            if (info.SignatureAlgorithmNotSupported)
                Console.WriteLine("  The algorithm " + info.DigestAlgorithm + " cannot be verified.");
            passed &= info.SignatureIsValid;

            // 3. The time-stamp of the signature.
            if (info.TimestampInfo != null)
                passed &= !info.TimestampInfo.IsTimestampAltered;

            // 4. The certificate of the signer, at the time of the time-stamp (now, without a time-stamp).
            if (info.SignatureType == SignatureType.DigitalSignature)
            {
                CertificateValidationResult result = CertificateValidator.Validate(info, new CertificateValidationSettings());
                Console.WriteLine("  Signer: " + info.SignatureCertificate.Subject + ", certificate: " + result.Status);
                foreach (string problem in result.Problems)
                    Console.WriteLine("    " + problem);

                passed &= result.IsTrusted;
            }
        }

        return passed;
    }
}
using (FileStream document = File.OpenRead("source[signed].pdf"))
{
    bool verified = PdfVerifier.Verify(document, LibrarySerialNumber);
    Console.WriteLine("Verified: " + verified);
}

The routine is a base to adapt: the trusted roots (CertificateValidationSettings.TrustedRoots, UseWindowsTrustedRoots) and the decision about an unknown revocation status (CertificateTrustStatus.RevocationUnknown) belong to your application. A document is verified from a stream like any other (section 6.12); LoadPdfDocument(byte[]) and LoadPdfDocument(string) work the same way. The sample project PDF Signature Verification is a complete program that also detects the format of the signature (PKCS#7 or PAdES, with a time-stamp, with validation data, with a document time-stamp). For the signatures that must be validated against the EU trusted lists, use the DSS validator (section 14.6).

6.12 Large documents: signing from a stream

The methods with byte[] and with a file path hold the whole document in memory, and the signed document is a second copy. For large documents, for example in a web service, the document can be signed from a stream, without being copied into memory:

PdfSignature pdfSignature = new PdfSignature(LibrarySerialNumber);
pdfSignature.DigitalSignatureCertificate = signingCertificate;
pdfSignature.SignatureStandard = PdfSignatureStandard.PadesLTA;
pdfSignature.TimeStamping.ServerUrl = new Uri("https://ca.signfiles.com/TSAServer.aspx");

using (FileStream input = File.OpenRead("large.pdf"))
using (FileStream output = File.Create("large[signed].pdf"))
{
    pdfSignature.LoadPdfDocument(input);       // the document is not read into memory
    pdfSignature.ApplyDigitalSignature(output); // the original is copied to output, followed by the new revision
}

// Verification, from a stream.
using (FileStream signed = File.OpenRead("large[signed].pdf"))
{
    PdfSignature reader = new PdfSignature(LibrarySerialNumber);
    reader.LoadPdfDocument(signed);
    foreach (PdfSignatureInfo info in reader.DocumentProperties.DigitalSignatures)
        Console.WriteLine(info.SignatureName + ": " + info.SignatureIsValid + ", level " + info.Level);
}

In some cases the document cannot be signed incrementally from its stream, and the library reads it into memory (the result is the same):

The methods that return a byte[] (ApplyDigitalSignature(), ApplyTimestampSignature(), AddArchiveTimestamp()) also work after LoadPdfDocument(Stream), but the result is the whole document in memory.

The 2 GB limit

The PDF documents of 2 GB or more are not supported: the positions of a PDF document (cross-reference table, byte range of a signature) are 32-bit integers in the PDF engine of the library, and the byte ranges above 231−1 are outside the limits of the common PDF readers. LoadPdfDocument(Stream) throws IOException before it reads such a document (a stream that is not seekable is stopped when it reaches 2 GB), and a document that would reach 2 GB with its new revision is refused with IOException too. For files of this size, use a detached CAdES signature (.p7s), which has no size limit (section 7.6).

6.13 Merging, adding texts and images

PdfMerge.MergePdfFiles(List<byte[]>) merges documents (the metadata of the first one is kept). PdfInsertObject adds images (over or under the content, as a stamp or a full-page watermark) and texts to the pages. Do it before the document is signed: these classes rewrite the document, and a change after the signature invalidates it. PdfInsertObject.InsertObjects refuses a signed document with InvalidOperationException, unless AllowSignatureInvalidation is true.

// Merge two documents.
byte[] merged = PdfMerge.MergePdfFiles(new List<byte[]>
{
    File.ReadAllBytes("contract.pdf"),
    File.ReadAllBytes("annex.pdf")
});

// Add a text and a stamp image.
PdfInsertObject insert = new PdfInsertObject();
insert.LoadPdfDocument(merged);

CustomText text = new CustomText();
text.Text = "APPROVED";
text.FontSize = 24;
text.PageNumber = 1;
text.StartingPointPosition = new System.Drawing.Point(100, 700);
insert.AddText(text);

insert.AddImage(File.ReadAllBytes("stamp.png"), new System.Drawing.Point(400, 50), 1, ImagePosition.ImageOverContent);   // page 1; page 0 = all the pages

byte[] stamped = insert.InsertObjects();

The page number 0 of an image or of a text means all the pages (CustomText.PageNumber is 0 by default). An image can also cover the page (AddImage(image, page, position)), for a watermark under the content (ImagePosition.ImageUnderContent). A text is written with Helvetica Bold, 12 points by default; it can use a TrueType font (CustomText.FontFile), a color (TextColor, a System.Drawing.Color; black when it is null), an alignment (Align, a TextAlign) and a direction (TextDirection).

6.14 Signature policy

A regulation can require an explicit signature policy in the signature. SetSignaturePolicyInformation(oid, policyHash, hashAlgorithmOid, url) adds the signature-policy-identifier attribute to the signatures created by the object; the same method exists in CadesSignature, XadesSignature, OfficeSignature and AsicSignature. policyHash is the hash of the policy document that you published or got from the authority; calling the method with null removes the policy.

// pdfSignature: the PdfSignature object of the previous examples (certificate set, document loaded)
byte[] policyDocument = File.ReadAllBytes("policy.pdf");
byte[] policyHash = SHA256.Create().ComputeHash(policyDocument);

pdfSignature.SignatureStandard = PdfSignatureStandard.Pades;
pdfSignature.SetSignaturePolicyInformation("2.16.76.1.7.1.5.2.3", policyHash, "2.16.840.1.101.3.4.2.1", "http://ca.example.com/policy.pdf");

6.15 PDF readers and validators

7. CAdES and PKCS#7 signatures (.p7m, .p7s)

CadesSignature signs any file or data (a PDF, an image, an archive, an XML file, text) as a CMS / PKCS#7 or CAdES signature. The result is a file with the extension .p7m when it contains the signed document (an attached signature) or .p7s when it contains only the signature (a detached signature). CadesVerify reads and verifies these files. CAdES (ETSI EN 319 122-1) is the format that the eIDAS Regulation uses for the signatures of files of any type.

7.1 Creating a signature

CadesSignature cadesSignature = new CadesSignature(LibrarySerialNumber);

cadesSignature.DigitalSignatureCertificate = signingCertificate;
cadesSignature.HashAlgorithm = SignLib.HashAlgorithm.SHA256;
cadesSignature.SignatureStandard = CadesSignatureStandard.CadesBes;

// A file: the result is the content of the .p7m file (the signed file is inside).
byte[] p7m = cadesSignature.ApplyDigitalSignature("contract.pdf");
File.WriteAllBytes("contract.pdf.p7m", p7m);

// Data in memory.
byte[] data = File.ReadAllBytes("contract.pdf");
byte[] p7mFromData = cadesSignature.ApplyDigitalSignature(data);
PropertyMeaning
DigitalSignatureCertificateThe signing certificate (section 5.2); the missing certificate throws NullReferenceException.
SignatureStandardThe format: CadesBes (the default), Cms, CadesT, CadesC, CadesXL, CadesA, CadesLT, CadesLTA (section 7.2).
HashAlgorithmSHA256 by default (SHA384, SHA512; SHA1 only for old systems).
IsDetachedSignaturetrue: the signature does not contain the document (.p7s). Default false (.p7m). It applies to the signature of a document; a co-signature keeps the packaging of the existing signature (section 7.5).
CoSignExistingSignaturetrue (default): data that is itself a CMS signature (a .p7m or .p7s file) is co-signed, a new signer is added to it. false: the data is always signed as a document (section 7.5).
TimeStampingThe time-stamping server (section 11). When TimeStamping.ServerUrl is set, the signature is time-stamped.
LtvLevel (CadesLtvLevel)The revocation data of the long term levels (CadesC, CadesXL, CadesA, CadesLT, CadesLTA): IncludeOcspOnly (the default), IncludeCrlAndOcsp, IncludeCrl or None (section 7.3).
AllowIncompleteValidationDatafalse (default): a long term signature whose revocation data cannot be obtained is not created (ValidationDataException). true: it is created with the data that could be obtained.
MaxCrlSizeThe CRLs larger than this value (in bytes, 20 MB by default) are not embedded in the long term levels.
MimeTypeThe media type of the signed document (for example application/pdf), written in the mime-type signed attribute of the CadesLT and CadesLTA signatures. When it is not set, it is taken from the extension of the file given to ApplyDigitalSignature(string) (application/octet-stream for an unknown extension); without MimeType, the attribute is not added when data in memory or a stream is signed, or when a signature is co-signed.
SetSignaturePolicyInformation(...)An explicit signature policy (section 7.8).

The method returns the bytes of the signature; the library writes nothing on the disk. ApplyDigitalSignature(Stream input, Stream output) signs a stream and writes the signature to another stream, for large files (section 7.6). The signature is RSA (PKCS#1 v1.5) or ECDSA, as the key of the certificate; for ECDSA certificates the signature value is converted to the DER form that CMS requires. The errors of the signature are reported as CryptographicException.

7.2 The levels of CAdES

The enumeration CadesSignatureStandard contains the formats that the older and the newer specifications define:

ValueContent of the signatureNetwork
CmsCMS / PKCS#7 signature (RFC 5652), recognized by the older software. No ETSI attribute.No (except the time-stamp)
CadesBesCAdES-B-B (basic electronic signature): the signing certificate is referenced by the signed attribute signing-certificate-v2 (signing-certificate for SHA-1). With TimeStamping.ServerUrl, the signature time-stamp is added: the signature is CAdES-B-T, the same as with CadesT.The TSA, when it is used
CadesTCAdES-B-T (CAdES-T): CadesBes and the signature time-stamp (the signature-time-stamp unsigned attribute), which proves that the signature existed at the time of the time-stamp. No validation data. It requires TimeStamping.ServerUrl: without it, ApplyDigitalSignature throws NullReferenceException and no signature is created.TSA (required)
CadesCCAdES-C: the signature time-stamp (CAdES-T), the complete references of the certificates and of the revocation data, with their values.CRL, OCSP, TSA (required)
CadesXLCAdES-X Long: CAdES-C and a time-stamp of the references (escTimeStamp).CRL, OCSP, TSA (required)
CadesACAdES-A (archival, ETSI TS 101 733): the values of the certificates and of the revocation data in unsigned attributes (certificate-values, revocation-values) and an archive time-stamp (version 3, ETSI EN 319 122-1) of the signature and of its validation data. The validators (for example DSS) report it as CAdES-A, not as a baseline level: for B-LTA use CadesLTA.CRL, OCSP, TSA (required)
CadesLTCAdES-B-LT (ETSI EN 319 122-1): a signature time-stamp, and the certificates and the revocation data (CRLs and OCSP responses) of the signing certificate and of the time-stamp, written in the certificates and crls fields of the SignedData (not in unsigned attributes). The mime-type signed attribute is added (MimeType). Validators report it as CAdES-BASELINE-LT.CRL, OCSP, TSA (required)
CadesLTACAdES-B-LTA (long term archival, ETSI EN 319 122-1): CadesLT and an archive time-stamp (version 3) of the signature and of all its validation data. Validators report it as CAdES-BASELINE-LTA. The format to use for archives.CRL, OCSP, TSA (required)

All the levels with validation data (CadesC, CadesXL, CadesA, CadesLT, CadesLTA) are built on the signature time-stamp and require TimeStamping.ServerUrl: without it, ApplyDigitalSignature throws NullReferenceException and no signature is created. They are created only when they are complete (unless AllowIncompleteValidationData is true):

CAdES-EPES (explicit policy) is a CadesBes signature with a policy set by SetSignaturePolicyInformation. The validation data is collected from the addresses in the certificates; a self-signed (root) certificate needs none. The idea of the levels is in section 12.

// The same file, signed with every level (CadesT and the levels with validation data need the time-stamping server).
CadesSignatureStandard[] levels =
{
    CadesSignatureStandard.Cms, CadesSignatureStandard.CadesBes, CadesSignatureStandard.CadesT,
    CadesSignatureStandard.CadesC, CadesSignatureStandard.CadesXL, CadesSignatureStandard.CadesA,
    CadesSignatureStandard.CadesLT, CadesSignatureStandard.CadesLTA
};

foreach (CadesSignatureStandard level in levels)
{
    CadesSignature cadesSignature = new CadesSignature(LibrarySerialNumber);
    cadesSignature.DigitalSignatureCertificate = signingCertificate;
    cadesSignature.SignatureStandard = level;
    cadesSignature.TimeStamping.ServerUrl = new Uri("https://ca.signfiles.com/TSAServer.aspx");

    File.WriteAllBytes("test.txt[" + level + "].p7m", cadesSignature.ApplyDigitalSignature("test.txt"));
}

Renewal of CAdES-LTA. AddArchiveTimestamp(signature, detachedContent) adds to the SignedData the validation data of the time-stamping authority of the last archive time-stamp of each CAdES-LTA signer, then a new archive-time-stamp-v3, which covers the previous ones. detachedContent is the signed document of a detached signature, otherwise null. The signing certificate is not needed; TimeStamping, LtvLevel, MaxCrlSize and AllowIncompleteValidationData are used. A signature without a CAdES-LTA signer throws InvalidOperationException, and a CAdES-LTA signer that is not valid, CryptographicException.

CadesSignature renewal = new CadesSignature(LibrarySerialNumber);
renewal.TimeStamping.ServerUrl = new Uri("https://ca.signfiles.com/TSAServer.aspx");

byte[] renewed = renewal.AddArchiveTimestamp(File.ReadAllBytes("contract.pdf.p7m"), null);
File.WriteAllBytes("contract.pdf.p7m", renewed);

When to renew (LongTermArchive.GetCadesRenewalDate) is in section 12.6.

7.3 The revocation data of the long term levels

LtvLevel selects the revocation data that the levels CadesC, CadesXL, CadesA, CadesLT and CadesLTA embed, for the certificate chains of the signer and of the time-stamping authority (the roots excepted). It has no effect on the Cms and CadesBes signatures, which have no validation data. The downloaded data is reused by the next signatures of the process, except the OCSP responses, which are requested after the signature time-stamp (section 12.5).

ValueEmbedded revocation data
IncludeOcspOnlyThe default, and the smallest signature. The OCSP response of the signing certificate (and of the time-stamping certificate), its CRL only when the OCSP response is not available; the CRLs of the CA certificates, their OCSP responses only when the CRL is not available. A large CRL of the signing certificate is not downloaded when the OCSP responder answers.
IncludeCrlAndOcspThe CRL and the OCSP response of every certificate.
IncludeCrlThe CRL of every certificate, without OCSP responses.
NoneNo revocation data. Accepted only with AllowIncompleteValidationData = true; the signature is then not a complete long term signature, and a validator reports a lower level (for example CAdES-BASELINE-T instead of CAdES-BASELINE-LT).
CadesSignature cadesSignature = new CadesSignature(LibrarySerialNumber);
cadesSignature.DigitalSignatureCertificate = signingCertificate;
cadesSignature.SignatureStandard = CadesSignatureStandard.CadesLT;
cadesSignature.TimeStamping.ServerUrl = new Uri("https://ca.signfiles.com/TSAServer.aspx");

// The CRLs and the OCSP responses, instead of the default IncludeOcspOnly.
cadesSignature.LtvLevel = CadesLtvLevel.IncludeCrlAndOcsp;

File.WriteAllBytes("contract.pdf.p7m", cadesSignature.ApplyDigitalSignature("contract.pdf"));

7.4 Detached signatures (.p7s)

With IsDetachedSignature = true the result is only the signature. The signed file is not changed, and it is needed to verify the signature. This is the convenient form for large files or when the original must stay untouched; the attached form (.p7m) is one file that cannot lose its document. The detached signature of a file (ApplyDigitalSignature(string)) is computed from the digests of the file, read once, without reading the file into memory, at every level.

CadesSignature cadesSignature = new CadesSignature(LibrarySerialNumber);
cadesSignature.DigitalSignatureCertificate = signingCertificate;
cadesSignature.IsDetachedSignature = true;

File.WriteAllBytes("contract.pdf.p7s", cadesSignature.ApplyDigitalSignature("contract.pdf"));

7.5 Co-signatures

When the data that you give to ApplyDigitalSignature is itself a CMS signature (a .p7m file), the library adds a new signature to it, instead of signing the signature again: the result is one file with all the signers, and the existing signatures stay valid. The existing signers, certificates, CRLs, OCSP responses, the content and its packaging are kept. Call it once for every co-signer, with the certificate of that signer.

// The first signer.
CadesSignature first = new CadesSignature(LibrarySerialNumber);
first.DigitalSignatureCertificate = signingCertificate;
byte[] signed = first.ApplyDigitalSignature("contract.pdf");

// The second and the third signer add their signatures to the same file.
X509Certificate2 secondCertificate = DigitalCertificate.LoadCertificate("second.pfx", "123456");
X509Certificate2 thirdCertificate = DigitalCertificate.LoadCertificate("third.pfx", "123456");

foreach (X509Certificate2 coSigner in new[] { secondCertificate, thirdCertificate })
{
    CadesSignature next = new CadesSignature(LibrarySerialNumber);
    next.DigitalSignatureCertificate = coSigner;
    signed = next.ApplyDigitalSignature(signed);
}

File.WriteAllBytes("contract.pdf.p7m", signed);
// A detached signature and its document: a second signer.
CadesSignature coSigner = new CadesSignature(LibrarySerialNumber);
coSigner.DigitalSignatureCertificate = signingCertificate;
byte[] coSigned = coSigner.ApplyDigitalSignature(File.ReadAllBytes("contract.pdf.p7s"), File.ReadAllBytes("contract.pdf"));
File.WriteAllBytes("contract.pdf.p7s", coSigned);

// The .p7m signed as a document, in a new signature that contains it: contract.pdf.p7m.p7m.
CadesSignature outer = new CadesSignature(LibrarySerialNumber);
outer.DigitalSignatureCertificate = signingCertificate;
outer.CoSignExistingSignature = false;
File.WriteAllBytes("contract.pdf.p7m.p7m", outer.ApplyDigitalSignature("contract.pdf.p7m"));

7.6 Large files: signing and verifying streams

The methods with byte[] hold the document in memory, and an attached signature of a file (ApplyDigitalSignature(string) with IsDetachedSignature = false) reads the file into memory too. For large files the signature is created and verified from streams, at every level (Cms to CadesLTA), and the CAdES signatures have no size limit (they are tested with documents of 5 GB):

CadesSignature cadesSignature = new CadesSignature(LibrarySerialNumber);
cadesSignature.DigitalSignatureCertificate = signingCertificate;
cadesSignature.SignatureStandard = CadesSignatureStandard.CadesLTA;
cadesSignature.TimeStamping.ServerUrl = new Uri("https://ca.signfiles.com/TSAServer.aspx");
cadesSignature.IsDetachedSignature = true;

// Signing: the document is read once, the .p7s file is written.
using (FileStream document = File.OpenRead("archive.zip"))
using (FileStream signature = File.Create("archive.zip.p7s"))
{
    cadesSignature.ApplyDigitalSignature(document, signature);
}

// Verification of the detached signature: the document is read once.
using (FileStream document = File.OpenRead("archive.zip"))
{
    CadesVerify verify = new CadesVerify(File.ReadAllBytes("archive.zip.p7s"), document, LibrarySerialNumber);
    Console.WriteLine("Intact: " + verify.Signatures.All(s => s.SignatureIsValid) + ", level " + verify.Level);
}
// An attached signature (.p7m) of a large file, and the extraction of the document when it is verified.
CadesSignature cadesSignature = new CadesSignature(LibrarySerialNumber);
cadesSignature.DigitalSignatureCertificate = signingCertificate;

using (FileStream document = File.OpenRead("video.mp4"))              // seekable: read two times
using (FileStream signature = File.Create("video.mp4.p7m"))
{
    cadesSignature.ApplyDigitalSignature(document, signature);
}

using (FileStream signature = File.OpenRead("video.mp4.p7m"))
using (FileStream extracted = File.Create("video[extracted].mp4"))
{
    CadesVerify verify = new CadesVerify(signature, extracted, LibrarySerialNumber);
    Console.WriteLine("Intact: " + verify.Signatures.All(s => s.SignatureIsValid));
}
Prefer a detached signature for very large files

An attached signature (.p7m) is as large as the document, and many applications cannot open a .p7m of several GB. A detached signature (.p7s) is small, the document stays unchanged, and it is read only once when it is signed and when it is verified. PDF documents of 2 GB or more cannot be signed as PDF (section 6.12): sign them with a detached CAdES signature.

7.7 Verifying a signature

The constructor of CadesVerify reads and verifies the signature; the object then has the result. A signature can be in binary (DER) form or in Base64 text, with or without the -----BEGIN ...----- lines.

ConstructorUse
CadesVerify(string signedFile, string serialNumber)A .p7m file (attached) from the disk. DocumentName is the name of the signed document: the document name signed attribute, or the file name without its extension (contract.pdf.p7m → contract.pdf).
CadesVerify(byte[] signedArray, string serialNumber)A .p7m in memory.
CadesVerify(byte[] detachedSignature, byte[] originalFile, string serialNumber)A detached signature (.p7s) and the document that it signs.
CadesVerify(Stream signedFile, Stream documentOutput, string serialNumber)A signature read from a stream; the document is copied to documentOutput (or null) and not held in memory (section 7.6).
CadesVerify(byte[] detachedSignature, Stream originalFile, string serialNumber)A detached signature and its document read from a stream (section 7.6).
MemberMeaning
Signatures (List<CadesSignatureInfo>)The signers, in the order of the signature.
SignatureStandard, LevelThe format (Cms, CadesBes, CadesT, ... CadesA, CadesLT, CadesLTA) and the effective level (SignatureLevel: B, T, LT, LTA) of the signature: the lowest of its signers. A signature with an archive time-stamp and the validation data only in the SignedData is CadesLTA; with the values in unsigned attributes, CadesA. A chain that needs no revocation data (self-signed certificates) is CadesLT / CadesLTA when its level is LT / LTA. A CAdES-BES signature with the signature time-stamp and without the validation data of B-LT is CadesT, with Level = T, also when it was signed as CadesBes with TimeStamping.ServerUrl.
UnsignedDocumentThe signed document (byte[]) of an attached signature: the way to extract the file from a .p7m. null for a detached signature verified without the document, and with the stream constructor.
CadesSignatureInfo.SignatureIsValidThe integrity: the signed data was not changed and the signature matches the certificate, which must be the one named by the signing-certificate attribute when the signature has it (not the trust of the certificate).
SignatureAlgorithmNotSupportedtrue when the signature or digest algorithm is not known to the library: the signature could not be verified, SignatureIsValid is false, but the signature was not found altered.
SignatureStandard, Level (of a signer)The format and the effective level of this signer, detected from its attributes; Level is None for a signature that is not an AdES signature or that is not valid (section 12.4).
ValidationDataComplete, MissingValidationDataWhether the signature contains an OCSP response or a CRL for every certificate (except the root) of the chains of the signer and of the time-stamping authority of the signature time-stamp, valid at the time of the time-stamp; otherwise the certificates without data.
SignatureCertificateThe signing certificate, or null when the signature does not contain it.
SignatureTimeThe signing time that the signer declared (UTC), or DateTime.MinValue when there is none. Not a proof (section 4.6).
SignatureIsTimestamped, TimestampInfoThe time-stamp of the signature, when it has one (section 11.3). A time-stamp counts only when its message imprint is the hash of the signature value and its signature is valid; a time-stamp that does not belong to the signature has TimestampInfo.IsTimestampAltered true.
HashAlgorithm (Oid), SignatureHashThe hash algorithm of the signer (HashAlgorithm.FriendlyName: sha256) and the signature value.

Algorithms. The library signs with RSA (PKCS#1 v1.5) and ECDSA, with SHA-1, SHA-256, SHA-384 or SHA-512. It verifies, in addition, the signatures that other software creates with RSASSA-PSS, with ECDSA and SHA-224 or SHA-3, and with Ed25519.

CadesVerify cadesVerify = new CadesVerify("contract.pdf.p7m", LibrarySerialNumber);

Console.WriteLine("Format: " + cadesVerify.SignatureStandard + ", level " + cadesVerify.Level + ", signers: " + cadesVerify.Signatures.Count);

foreach (CadesSignatureInfo signer in cadesVerify.Signatures)
{
    string name = signer.SignatureCertificate != null
        ? signer.SignatureCertificate.GetNameInfo(X509NameType.SimpleName, false)
        : "(the certificate is not in the signature)";

    Console.WriteLine(name + ", hash " + signer.HashAlgorithm.FriendlyName + ", intact: " + signer.SignatureIsValid
        + (signer.SignatureAlgorithmNotSupported ? " (algorithm not supported)" : string.Empty)
        + (signer.SignatureIsTimestamped ? ", time-stamped " + signer.TimestampInfo.SignatureTime.ToLocalTime() : string.Empty)
        + ", validation data complete: " + signer.ValidationDataComplete);

    foreach (MissingValidationData missing in signer.MissingValidationData)
        Console.WriteLine("  No revocation data: " + missing.Subject + " (" + missing.Reason + ")");
}

// Extract the signed document.
File.WriteAllBytes(cadesVerify.DocumentName ?? "document", cadesVerify.UnsignedDocument);

// A detached signature: the document is a parameter.
CadesVerify detached = new CadesVerify(File.ReadAllBytes("contract.pdf.p7s"), File.ReadAllBytes("contract.pdf"), LibrarySerialNumber);
bool allIntact = detached.Signatures.All(s => s.SignatureIsValid);

7.8 Signature policy

A policy that a regulation requires is added with SetSignaturePolicyInformation. The OID of the policy, the hash of the policy document and the hash algorithm (as an OID) are written in the signed attributes; the URL of the document is optional.

byte[] policyHash = SHA256.Create().ComputeHash(File.ReadAllBytes("policy.pdf"));

CadesSignature cadesSignature = new CadesSignature(LibrarySerialNumber);
cadesSignature.DigitalSignatureCertificate = signingCertificate;
cadesSignature.SetSignaturePolicyInformation("2.16.76.1.7.1.5.2.3", policyHash, "2.16.840.1.101.3.4.2.1", "http://ca.example.com/policy.pdf");

byte[] p7m = cadesSignature.ApplyDigitalSignature("contract.pdf");

7.9 Notes

8. XML signatures: XMLDSig and XAdES

Two classes sign XML:

Both classes use the same technique for the signatures, which allows several signatures in the same document, and the same methods to read and verify them.

8.1 XMLDSig: sign and verify

XmlSignature xmlSignature = new XmlSignature(LibrarySerialNumber);

xmlSignature.DigitalSignatureCertificate = signingCertificate;
xmlSignature.HashAlgorithm = SignLib.HashAlgorithm.SHA256;

// The signed document: the signature element is added inside it.
xmlSignature.ApplyDigitalSignature("test.xml", "test[signed].xml");

// Verification.
Console.WriteLine("Signatures: " + xmlSignature.GetNumberOfSignatures("test[signed].xml"));
Console.WriteLine("Algorithm: " + xmlSignature.GetSignatureAlgorithm("test[signed].xml"));   // for example RSA-SHA256
Console.WriteLine("All valid: " + xmlSignature.VerifyDigitalSignature("test[signed].xml"));
PropertyMeaning
HashAlgorithmSHA256 (default), SHA384, SHA512. SHA1 is not supported for new signatures (NotSupportedException); the existing SHA-1 signatures are verified, unless XmlSignatureVerificationPolicy.RejectSha1 is true (section 8.7).
SignatureType (XmlSignatureType)The canonicalization of the signed data: Default (Canonical XML 1.0, the default), DefaultWithComments, Exclusive (Exclusive XML Canonicalization), ExclusiveWithComments. The signature method follows the key: rsa-sha256/384/512 or ecdsa-sha256/384/512 (RFC 6931).
IncludeKeyInfoInclude the key of the signer in the signature (true by default): the RSA key value, or the certificate for an ECDSA key.
IncludeSignatureCertificateInclude the signing certificate (X509Certificate in KeyInfo), true by default. Without it, verification with VerifyDigitalSignature(file, certificate) needs the certificate.
PreserveWhitespacetrue (default): the white space of the document is kept exactly, and the signed document is written as it was. false: the insignificant white space is removed when the document is loaded and the result is indented.

The result is an XML document with a Signature element (shortened):

<Signature Id="Signature-c5ebc05f5292a6e2" xmlns="http://www.w3.org/2000/09/xmldsig#">
  <SignedInfo>
    <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
    <SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />
    <Reference URI="">
      <Transforms>
        <Transform Algorithm="http://www.w3.org/TR/1999/REC-xpath-19991116">
          <XPath xmlns:ds="http://www.w3.org/2000/09/xmldsig#">not(ancestor-or-self::ds:Signature)</XPath>
        </Transform>
        <Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
      </Transforms>
      <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
      <DigestValue>ljCeDlHjth920eC4V7sbhf2ohGqrtkDXa4oQ/1ZerMs=</DigestValue>
    </Reference>
  </SignedInfo>
  <SignatureValue>eqfjZXq9igQEaxqs...</SignatureValue>
  <KeyInfo>
    <KeyValue><RSAKeyValue><Modulus>la21u9LP...</Modulus><Exponent>AQAB</Exponent></RSAKeyValue></KeyValue>
    <X509Data><X509Certificate>MIIDZTCCAk2gAwIB...</X509Certificate></X509Data>
  </KeyInfo>
</Signature>

The signature references the whole document (URI="") with an XPath transform that removes all the Signature elements, instead of the usual enveloped-signature transform that removes only the signature that contains it. This is the standard construction for parallel signatures: a signature that is added later is not part of the digest of the first one, so every signature stays valid.

Several signatures, reading and verifying

XmlSignature xmlSignature = new XmlSignature(LibrarySerialNumber);

// Add a second signer to the document that is already signed.
X509Certificate2 secondSigner = DigitalCertificate.LoadCertificate("second.pfx", "123456");
xmlSignature.DigitalSignatureCertificate = secondSigner;
xmlSignature.ApplyDigitalSignature("test[signed].xml", "test[signed].xml");

int count = xmlSignature.GetNumberOfSignatures("test[signed].xml");

for (int index = 0; index < count; index++)
{
    X509Certificate2 signer = xmlSignature.GetDigitalSignatureCertificate("test[signed].xml", index);
    Console.WriteLine(index + ": " + signer.GetNameInfo(X509NameType.SimpleName, false)
        + ", valid: " + xmlSignature.VerifyDigitalSignature("test[signed].xml", index));
}

// Was the document signed by the expected certificate?
bool signedBySecond = xmlSignature.VerifyDigitalSignature("test[signed].xml", secondSigner);

// In memory (a web application).
using (MemoryStream input = new MemoryStream(File.ReadAllBytes("test.xml")))
using (MemoryStream output = new MemoryStream())
{
    xmlSignature.DigitalSignatureCertificate = signingCertificate;
    xmlSignature.ApplyDigitalSignature(input, output);
    byte[] signedXml = output.ToArray();
}
Any change of the document invalidates the signatures

A signature covers the canonical form of the XML. Changing a value, the order of the elements or the text of the document (including re-saving it with another encoding) invalidates it. The white space between the elements is part of the signed data: reformatting or indenting a signed document changes it. Keep the signed file as it is, and load and save it with the encoding that its XML declaration declares.

8.2 XAdES

XadesSignature follows the same pattern as XmlSignature, with the properties of the ETSI standard:

PropertyMeaning
SignatureStandard (XadesSignatureStandard)XadesB (B-B, the default), XadesT (+ time-stamp), XadesLT (+ validation data), XadesLTA (+ archive time-stamp). T, LT and LTA require TimeStamping.ServerUrl (ArgumentException otherwise). A XadesB signature is also time-stamped (B-T) when the server is set.
SignaturePackagingEnveloped (default): the signature is in the XML document, only an XML document can be signed. Detached: the signature is a separate XML file that references the signed file, of any type; the signed file is needed to verify it.
HashAlgorithmSHA256 (default), SHA384, SHA512 (not SHA-1).
CommitmentType (XadesCommitmentType)What the signer declares: None (default, not written), ProofOfOrigin, ProofOfReceipt, ProofOfDelivery, ProofOfSender, ProofOfApproval, ProofOfCreation. It is a signed property: the signer commits to it.
SignatureProductionPlace (XadesProductionPlace)City, street address, state or province, postal code and country (an ISO code such as RO). All the fields are optional.
LtvLevel (XadesLtvLevel)The revocation data of the LT and LTA levels: IncludeOcspOnly (default: the OCSP responses; the CRL of an end-entity certificate only when its OCSP response is not available; the CRLs of the CA certificates), IncludeCrlAndOcsp, IncludeCrl, None (see section 12).
MaxCrlSizeThe CRLs larger than this value are not included (1 MB by default).
AllowIncompleteValidationDatafalse (default): an LT or LTA signature whose revocation data cannot be obtained is not created (ValidationDataException, before the document is written; InvalidOperationException when LtvLevel is None). true: the signature is created with the data that could be obtained.
SetSignaturePolicyInformationAn explicit signature policy (section 6.14).
XadesSignature xadesSignature = new XadesSignature(LibrarySerialNumber);

xadesSignature.DigitalSignatureCertificate = signingCertificate;
xadesSignature.SignatureStandard = XadesSignatureStandard.XadesB;
xadesSignature.SignaturePackaging = XadesSignaturePackaging.Enveloped;
xadesSignature.CommitmentType = XadesCommitmentType.ProofOfApproval;
xadesSignature.SignatureProductionPlace = new XadesProductionPlace { City = "Bucharest", CountryName = "RO" };

xadesSignature.ApplyDigitalSignature("test.xml", "test[xades].xml");
Console.WriteLine("Valid: " + xadesSignature.VerifyDigitalSignature("test[xades].xml"));

A time-stamp and the long term levels

XadesSignature xadesSignature = new XadesSignature(LibrarySerialNumber);
xadesSignature.DigitalSignatureCertificate = signingCertificate;

xadesSignature.SignatureStandard = XadesSignatureStandard.XadesLT;       // XadesT, XadesLT or XadesLTA
xadesSignature.LtvLevel = XadesLtvLevel.IncludeCrlAndOcsp;
xadesSignature.TimeStamping.ServerUrl = new Uri("https://ca.signfiles.com/TSAServer.aspx");

xadesSignature.ApplyDigitalSignature("test.xml", "test[xades-lt].xml");

The LT and LTA levels contain the certificates and the revocation data (OCSP responses, CRLs) of the chains of the signer and of the time-stamping authority. When the data of a certificate cannot be obtained, the signature is not created: ValidationDataException lists the certificates and the reasons in MissingData (section 12.5). A revoked certificate stops the signing with CertificateRevokedException.

Detached signatures

The signature is saved in an XML file and the signed file is not changed. The signature file must be a different file from the signed one. To verify, give both the signature and the original file (the original can have been renamed: with a single signed file the data is matched whatever its name; its integrity is guaranteed by the digest of the reference).

XadesSignature xadesSignature = new XadesSignature(LibrarySerialNumber);
xadesSignature.DigitalSignatureCertificate = signingCertificate;
xadesSignature.SignaturePackaging = XadesSignaturePackaging.Detached;

xadesSignature.ApplyDigitalSignature("contract.pdf", "contract.pdf[signature].xml");

bool valid = xadesSignature.VerifyDigitalSignature("contract.pdf[signature].xml", "contract.pdf");
X509Certificate2 signer = xadesSignature.GetDigitalSignatureCertificate("contract.pdf[signature].xml");

Several signers of the same file create separate signature files. To put several signed files and their signatures in one file, use an ASiC-E container (section 10).

8.3 Verifying XAdES signatures

VerifyDigitalSignature, GetNumberOfSignatures, GetDigitalSignatureCertificate and GetSignatureAlgorithm work as for XmlSignature; a detached signature is verified with VerifyDigitalSignature(signatureFile, originalFile). The verification checks the digest of the signed data, the digest of the signed properties and the signature value, and that the signing certificate of the signed properties is the certificate of the signature.

GetSignatures(file) (enveloped signatures) and GetSignatures(signatureFile, originalFile) (detached signatures) return every signature of the document, in document order, as a List<XadesSignatureInfo>. A document without signatures gives an empty list.

XadesSignatureInfoMeaning
SignatureIsValidThe references and the signature value are valid.
SignatureCertificateThe signing certificate, or null when it is not in the signature.
SignatureIsTimestamped, TimestampInfoThe signature has a valid signature time-stamp over its signature value; its information (section 11.3), or null.
Level (SignatureLevel)The level that the signature actually has, determined from what it contains: B, T, LT, LTA; None for an XMLDSig signature without XAdES properties or for a signature that is not valid (section 12.4).
ValidationDataComplete, MissingValidationDataThe signature contains an OCSP response or a CRL for every certificate (except the root) of the chains of the signer and of the time-stamping authority, valid at the time of the time-stamp; otherwise the certificates without data and the reasons.
ArchiveTimestamps, InvalidArchiveTimestampCountThe valid archive time-stamps (only they make the signature LTA), and the number of archive time-stamps that are not valid (altered, not issued by a valid time-stamping certificate, not covering the signature, or not verifiable, for example a detached signature read without its original file).
XadesSignature xadesSignature = new XadesSignature(LibrarySerialNumber);

List<XadesSignatureInfo> signatures = xadesSignature.GetSignatures("test[xades-lt].xml");

for (int index = 0; index < signatures.Count; index++)
{
    XadesSignatureInfo info = signatures[index];
    string signer = info.SignatureCertificate != null ? info.SignatureCertificate.GetNameInfo(X509NameType.SimpleName, false) : "unknown";

    Console.WriteLine(index + ": " + signer + ", valid: " + info.SignatureIsValid + ", level: " + info.Level);

    if (info.SignatureIsTimestamped)
        Console.WriteLine("   time-stamp: " + info.TimestampInfo.SignatureTime.ToLocalTime());

    foreach (MissingValidationData missing in info.MissingValidationData)
        Console.WriteLine("   no validation data: " + missing.Subject + " (" + missing.Reason + ")");
}

// A detached signature: the signed file is needed.
List<XadesSignatureInfo> detached = xadesSignature.GetSignatures("contract.pdf[signature].xml", "contract.pdf");

These methods verify the signatures and report what they contain; they do not decide that the signers can be trusted. CertificateValidator.Validate(info, settings) validates the certificate of a XadesSignatureInfo at the time of its time-stamp, with the validation data embedded in the signature before the online sources (section 5.4). A complete validation according to eIDAS is the job of a validator (section 14.6).

8.4 Raising the level of a signature

ExtendSignature raises the XAdES signatures of a document to a higher level: B to T, LT or LTA; T to LT or LTA; LT to LTA. Only the missing parts are added (the signature time-stamp, the validation data, the archive time-stamp); a signature already at the level or above it is not changed. Use it, for example, to sign quickly at B-B and to add the time-stamp and the validation data later, in a batch.

XadesSignature xadesSignature = new XadesSignature(LibrarySerialNumber);
xadesSignature.TimeStamping.ServerUrl = new Uri("https://ca.signfiles.com/TSAServer.aspx");

// An enveloped signature to B-LTA.
xadesSignature.ExtendSignature("test[xades].xml", "test[xades-lta].xml", XadesSignatureStandard.XadesLTA);

// A detached signature to B-LT.
xadesSignature.ExtendSignature("contract.pdf[signature].xml", "contract.pdf[signature].xml", "contract.pdf", XadesSignatureStandard.XadesLT);

8.5 Renewing the archive time-stamp

A XAdES-LTA signature stays verifiable while the certificate chain of the time-stamping authority of its last archive time-stamp is valid and its algorithms are strong. AddArchiveTimestamp adds a new archive time-stamp to every XAdES-LTA signature of the document; before it, the certificates and the current revocation data of the previous time-stamps are added (xades141:TimeStampValidationData). The other signatures are not changed; a document without a XAdES-LTA signature, or with a XAdES-LTA signature that is not valid, throws CryptographicException. It needs TimeStamping.ServerUrl, uses LtvLevel, MaxCrlSize and AllowIncompleteValidationData, and does not need the certificate of the signers.

LongTermArchive.GetXadesRenewalDate(file) returns the date (UTC) before which the document must be renewed: the first expiry date of the certificate chain of the time-stamping authority of the last archive time-stamp, or null when no signature has an archive time-stamp. Renew with a margin, for example 90 days before this date (section 12.6).

XadesSignature xadesSignature = new XadesSignature(LibrarySerialNumber);
xadesSignature.TimeStamping.ServerUrl = new Uri("https://ca.signfiles.com/TSAServer.aspx");

DateTime? renewalDate = LongTermArchive.GetXadesRenewalDate("test[xades-lta].xml");

if (renewalDate.HasValue && renewalDate.Value - DateTime.UtcNow < TimeSpan.FromDays(90))
{
    // Enveloped signatures (the output can be the input file).
    xadesSignature.AddArchiveTimestamp("test[xades-lta].xml", "test[xades-lta].xml");
}

// A detached signature: the signed file is part of the time-stamped data.
xadesSignature.AddArchiveTimestamp("contract.pdf[signature-lta].xml", "contract.pdf[signature-lta].xml", "contract.pdf");

8.6 ECDSA

RSA and ECDSA certificates are supported for XMLDSig and XAdES. The signature value of ECDSA in XML is the raw concatenation r || s (RFC 4051), different from the DER form of CMS; the library produces the right form for every format. The ECDSA signature methods of RFC 6931 are registered when the runtime does not have them.

8.7 Documents from untrusted sources

The signed documents often come from outside: the library reads them so that a document cannot make it read local files, send requests or use all the memory (section 4.11).

SecurityLimits and XmlSignatureVerificationPolicy are static: set them once, when the application starts; they apply to the whole process.

8.8 Notes

9. Office documents

OfficeSignature signs Office Open XML documents: Word (.docx, .docm), Excel (.xlsx, .xlsm) and PowerPoint (.pptx, .pptm). It creates the package signatures that Microsoft Office 2010 and later create and verify (File > Info > Protect Document > Add a Digital Signature): a XAdES signature in the part /_xmlsignatures/sigN.xml of the package. Office, and the library, show the signatures in the same way. The signature can be invisible, or visible in a Word document, as a signature line.

The library does not need Office installed. The documents are processed in memory as Open Packaging Conventions packages (System.IO.Packaging); the library writes only the output file that you give, and no temporary files.

9.1 Signing a document

OfficeSignature officeSignature = new OfficeSignature(LibrarySerialNumber);

officeSignature.DigitalSignatureCertificate = signingCertificate;
officeSignature.SignatureComments = "I approve this document";        // "Purpose for signing this document" in Office

officeSignature.ApplyDigitalSignature("contract.docx", "contract[signed].docx");   // the output can be the input file

Console.WriteLine("Signatures: " + officeSignature.GetNumberOfSignatures("contract[signed].docx"));
Console.WriteLine("Valid: " + officeSignature.VerifyDigitalSignature("contract[signed].docx"));
PropertyMeaning
SignatureStandard (XadesSignatureStandard)XadesB (default), XadesT, XadesLT. T and LT need TimeStamping.ServerUrl. XadesLTA is not supported for Office documents (NotSupportedException).
HashAlgorithmSHA256 (default), SHA384, SHA512. SHA-1 is not supported for new signatures (NotSupportedException).
SignatureCommentsThe purpose of the signature, shown by Office as “Purpose for signing this document”.
CommitmentTypeThe commitment of the signer, shown by Office: for example ProofOfApproval is “Approved this document”.
SignerRoleThe role or the title of the signer (the claimed role).
SignatureProductionPlaceThe city, the state or province, the postal code and the country (the street address is not used by Office).
TimeStamping, LtvLevel, MaxCrlSizeThe time-stamp and the validation data of the levels T and LT (section 12). LtvLevel is IncludeOcspOnly by default, as for XAdES (section 8.2).
AllowIncompleteValidationDatafalse (default): an LT signature whose revocation data cannot be obtained is not created (ValidationDataException, before the document is written; InvalidOperationException when LtvLevel is None). true: the signature is created with the data that could be obtained (section 12.5).
SignatureLineThe visible signature, a signature line of a Word document (section 9.2). null (default): invisible.
SetSignaturePolicyInformationAn explicit signature policy. By default the policy is implied, as for the signatures that Office creates.

The signed parts of the package are the main part and all the parts that it uses, with their relationships. A document with signatures cannot be changed: any change invalidates them. A second signature does not invalidate the first.

// Several signers: the document is signed again; the previous signatures stay valid.
OfficeSignature secondSigner = new OfficeSignature(LibrarySerialNumber);
secondSigner.DigitalSignatureCertificate = DigitalCertificate.LoadCertificate("second.pfx", "123456");
secondSigner.SignerRole = "Reviewer";
secondSigner.CommitmentType = XadesCommitmentType.ProofOfApproval;
secondSigner.ApplyDigitalSignature("contract[signed].docx", "contract[signed].docx");

A time-stamp and validation data

OfficeSignature officeSignature = new OfficeSignature(LibrarySerialNumber);
officeSignature.DigitalSignatureCertificate = signingCertificate;

officeSignature.SignatureStandard = XadesSignatureStandard.XadesLT;       // XadesT: the time-stamp only
officeSignature.LtvLevel = XadesLtvLevel.IncludeCrlAndOcsp;
officeSignature.TimeStamping.ServerUrl = new Uri("https://ca.signfiles.com/TSAServer.aspx");

officeSignature.ApplyDigitalSignature("report.xlsx", "report[signed-lt].xlsx");

In memory

The byte array and the stream overloads avoid the files. A stream is signed in place: the signed document replaces its content, so the stream must be readable, writable, seekable and expandable: a MemoryStream created from a byte array has a fixed size, create an empty one and write the document in it. The document is signed in memory and written to the stream only when the signature succeeded: a failure (for example a time-stamping server that does not answer) leaves the stream unchanged.

OfficeSignature officeSignature = new OfficeSignature(LibrarySerialNumber);
officeSignature.DigitalSignatureCertificate = signingCertificate;

// A byte array.
byte[] signedArray = officeSignature.ApplyDigitalSignature(File.ReadAllBytes("contract.docx"));

// A stream (in place).
using (MemoryStream stream = new MemoryStream())
{
    byte[] unsigned = File.ReadAllBytes("contract.docx");
    stream.Write(unsigned, 0, unsigned.Length);
    stream.Position = 0;

    officeSignature.ApplyDigitalSignature(stream);
    File.WriteAllBytes("contract[signed].docx", stream.ToArray());
}

9.2 Visible signatures: signature lines (Word, Windows)

A signature line is the place in a Word document where a person signs: a rectangle with a line, the name and the title of the signer. When the document is signed, Word shows the signature on the line and marks it as invalid if the document is changed. OfficeSignatureLine describes it, and the property OfficeSignature.SignatureLine makes the signature visible. Signature lines work for Word documents only (.docx, .docm) and on Windows: the images of the line are EMF metafiles drawn with System.Drawing, so a visible signature and AddSignatureLine throw PlatformNotSupportedException on the other systems. A visible signature on a workbook or a presentation throws NotSupportedException. The invisible signatures, GetSignatureLines and the verification work on all the platforms.

OfficeSignatureLineMeaning
PlacementUseExistingOrAddNew: signs the first unsigned line, or adds a new line at the end of the document when there is none. UseExisting: signs an existing unsigned line (the one with SetupId, or the first one) and fails when there is none. AddNew: adds a new line at the end and signs it (the document must not be signed yet).
SetupIdThe identifier of the line to sign (a GUID), as returned by AddSignatureLine or listed by GetSignatureLines.
SuggestedSigner, SuggestedSignerTitle, SuggestedSignerEmail, SigningInstructionsThe data shown on a new line and in the signing window of Word. Empty SuggestedSigner: the name of the certificate is shown.
SignatureText, SignatureImage, ShowSignDateWhat is shown above the line when it is signed: a text (the name of the signer), a handwritten image (PNG, JPEG, BMP, GIF) and the date.
Alignment (OfficeSignatureLineAlignment), Width, HeightThe alignment of a new line, and its size in points (default 192 × 96).
OfficeSignature officeSignature = new OfficeSignature(LibrarySerialNumber);
officeSignature.DigitalSignatureCertificate = signingCertificate;

officeSignature.SignatureLine = new OfficeSignatureLine
{
    Placement = OfficeSignatureLinePlacement.UseExistingOrAddNew,
    SuggestedSigner = "John Smith",
    SuggestedSignerTitle = "Accounting manager",
    SigningInstructions = "Sign only after the verification of the document.",
    SignatureText = "John Smith",
    SignatureImage = File.ReadAllBytes("signature_image.jpg"),
    ShowSignDate = true
};

officeSignature.ApplyDigitalSignature("contract.docx", "contract[signed].docx");

A document for several signers

Add the signature lines of all the signers before the first signature (a signed document cannot be changed: InvalidOperationException), then every signer signs the line with the identifier that was returned. The lines can also be created in Word (Insert > Signature Line).

OfficeSignature prepare = new OfficeSignature(LibrarySerialNumber);

string managerLine = prepare.AddSignatureLine("contract.docx", "contract[lines].docx", new OfficeSignatureLine
{
    SuggestedSigner = "John Smith", SuggestedSignerTitle = "Manager"
});
string accountantLine = prepare.AddSignatureLine("contract[lines].docx", "contract[lines].docx", new OfficeSignatureLine
{
    SuggestedSigner = "Mary Jones", SuggestedSignerTitle = "Accountant", Alignment = OfficeSignatureLineAlignment.Right
});

foreach (OfficeSignatureLineInfo line in prepare.GetSignatureLines("contract[lines].docx"))
    Console.WriteLine(line.SetupId + ": " + line.SuggestedSigner + ", signed: " + line.IsSigned);

// Every signer signs his line.
OfficeSignature manager = new OfficeSignature(LibrarySerialNumber);
manager.DigitalSignatureCertificate = signingCertificate;
manager.SignatureLine = new OfficeSignatureLine { Placement = OfficeSignatureLinePlacement.UseExisting, SetupId = managerLine, ShowSignDate = true };
manager.ApplyDigitalSignature("contract[lines].docx", "contract[lines].docx");

OfficeSignature accountant = new OfficeSignature(LibrarySerialNumber);
accountant.DigitalSignatureCertificate = DigitalCertificate.LoadCertificate("accountant.pfx", "123456");
accountant.SignatureLine = new OfficeSignatureLine { Placement = OfficeSignatureLinePlacement.UseExisting, SetupId = accountantLine };
accountant.ApplyDigitalSignature("contract[lines].docx", "contract[lines].docx");

9.3 Reading and verifying the signatures

MethodResult
GetNumberOfSignatures(file | stream)The number of signatures.
VerifyDigitalSignature(file | stream)true when all the signatures are valid; a document without signatures throws CryptographicException.
VerifyDigitalSignature(file, int index)One signature (0-based).
VerifyDigitalSignature(file, X509Certificate2 certificate)true when a valid signature of the document was created with the certificate.
GetDigitalSignatureCertificate(file, index), GetSignatureAlgorithm(file, index)The certificate and the algorithm (for example RSA-SHA256, ECDSA-SHA384) of a signature.
GetSignatures(file | stream)A List<OfficeSignatureInfo>: every signature with its information and the result of its verification.
GetSignatureLines(file | stream)The signature lines of a Word document (OfficeSignatureLineInfo: SetupId, SuggestedSigner, IsSigned); an empty list for the other documents.

OfficeSignatureInfo: Index; Status (Success; ContentModified when the document was changed after it was signed; ReferenceNotFound when a signed part is missing; InvalidSignature); IsValid; Certificate, SignerName; SigningTime (UTC, declared by the signer); HasTimestamp, TimestampTime (UTC); HasValidationData (the signature includes certificates and revocation data); Level (SignatureLevel: the level that the signature actually has, B, T or LT; None for a signature without XAdES properties or that is not valid; section 12.4); ValidationDataComplete and MissingValidationData (an OCSP response or a CRL for every certificate, except the root, of the chains of the signer and of the time-stamping authority; otherwise the certificates without data and the reasons); SignatureAlgorithm; SignatureComments, CommitmentType, SignerRole; IsVisible and SetupId of the signature line.

OfficeSignature officeSignature = new OfficeSignature(LibrarySerialNumber);

foreach (OfficeSignatureInfo info in officeSignature.GetSignatures("contract[signed].docx"))
{
    Console.WriteLine(info.Index + ": " + info.SignerName + ", " + info.Status + ", " + info.SignatureAlgorithm);

    if (info.SigningTime.HasValue)
        Console.WriteLine("   signed " + info.SigningTime.Value.ToLocalTime() + ", purpose: " + info.SignatureComments);

    if (info.HasTimestamp)
        Console.WriteLine("   time-stamp " + info.TimestampTime.Value.ToLocalTime() + ", validation data: " + info.HasValidationData);

    Console.WriteLine("   level: " + info.Level + ", validation data complete: " + info.ValidationDataComplete);
    foreach (MissingValidationData missing in info.MissingValidationData)
        Console.WriteLine("   no validation data: " + missing.Subject + " (" + missing.Reason + ")");
}
What the verification checks

The verification checks the XML signature, the binding of the signing certificate of the XAdES signature and the digests of all the signed parts and relationships. A document that was changed after it was signed gives ContentModified. The trust of the signing certificate and the revocation are not checked (section 4.5); Office warns when the certificate is not trusted. The signatures that use SHA-1, as the older versions of Office create them, are verified, unless XmlSignatureVerificationPolicy.RejectSha1 is true (section 8.7).

9.4 Notes

10. ASiC-E containers

An ASiC-E container (Associated Signature Container, Extended; ETSI EN 319 162-1) is a single ZIP file (.asice) that holds any number of files, of any type, and their XAdES signatures. Many e-government systems use it for e-invoicing, e-procurement, e-tax and court filings. AsicSignature creates the containers, adds signatures (co-signatures), verifies them, reads their contents, raises the level of their signatures and renews their time-stamps. Every signature covers all the files of the container.

documents.asice (a ZIP file) mimetypefirst entry, stored, not compressed the signed filescontract.pdf, annexes/annex1.pdf, data.xml ... META-INF/manifest.xmlthe list of the files of the container META-INF/signatures.xml, signatures001.xml, ...one file of XAdES signatures for every signing operation; each signature covers all the files
An ASiC-E container. A new signature is a new signature file; the files and the existing signatures are not changed.

10.1 Creating a container

CreateContainer signs the files and writes the container in one operation. The files are stored under their names; with the dictionary overload the name is the path inside the container (for example annexes/annex1.pdf), and no file touches the disk.

AsicSignature asicSignature = new AsicSignature(LibrarySerialNumber);
asicSignature.DigitalSignatureCertificate = signingCertificate;

// From files: the container is written to the output path (and deleted when the signature fails).
asicSignature.CreateContainer(new[] { "contract.pdf", "data.xml" }, "documents.asice");

// From memory: the names are the paths in the container.
IDictionary<string, byte[]> files = new Dictionary<string, byte[]>
{
    { "contract.pdf", File.ReadAllBytes("contract.pdf") },
    { "annexes/annex1.pdf", File.ReadAllBytes("annex1.pdf") }
};
byte[] container = asicSignature.CreateContainer(files);
File.WriteAllBytes("documents[memory].asice", container);

The names must be safe relative paths: no absolute path, no .., no backslash, no META-INF or mimetype, and unique (ArgumentException otherwise). A file that does not exist throws FileNotFoundException.

PropertyMeaning
SignatureStandard (XadesSignatureStandard)XadesB (default), XadesT, XadesLT, XadesLTA. T, LT and LTA need TimeStamping.ServerUrl.
HashAlgorithmSHA256 (default), SHA384, SHA512 (not SHA-1).
TimeStamping, LtvLevel, MaxCrlSizeThe time-stamp and the validation data (section 12). LtvLevel is IncludeOcspOnly by default, as for XAdES (section 8.2).
AllowIncompleteValidationDatafalse (default): an LT or LTA signature, an extension or a renewal whose revocation data cannot be obtained is not made (ValidationDataException, before the container is written; InvalidOperationException when LtvLevel is None). true: the signature is created with the data that could be obtained (section 12.5).
CommitmentType, SignatureProductionPlaceThe signed properties of XAdES (section 8.2).
SetSignaturePolicyInformationAn explicit signature policy.
AsicSignature asicSignature = new AsicSignature(LibrarySerialNumber);
asicSignature.DigitalSignatureCertificate = signingCertificate;

asicSignature.SignatureStandard = XadesSignatureStandard.XadesLT;
asicSignature.LtvLevel = XadesLtvLevel.IncludeCrlAndOcsp;
asicSignature.TimeStamping.ServerUrl = new Uri("https://ca.signfiles.com/TSAServer.aspx");
asicSignature.HashAlgorithm = SignLib.HashAlgorithm.SHA384;
asicSignature.CommitmentType = XadesCommitmentType.ProofOfApproval;
asicSignature.SignatureProductionPlace = new XadesProductionPlace { City = "Bucharest", CountryName = "RO" };

asicSignature.CreateContainer(new[] { "contract.pdf", "data.xml" }, "documents[lt].asice");

10.2 Co-signatures

AddSignature adds a signature of another signer. The new signature covers all the files and goes to a new signature file; the existing signatures are not changed. Set the certificate of the new signer on the object first.

AsicSignature secondSigner = new AsicSignature(LibrarySerialNumber);
secondSigner.DigitalSignatureCertificate = DigitalCertificate.LoadCertificate("second.pfx", "123456");

// Files (the output can be the input container).
secondSigner.AddSignature("documents.asice", "documents[cosigned].asice");

// In memory.
byte[] cosigned = secondSigner.AddSignature(File.ReadAllBytes("documents.asice"));

10.3 Reading and verifying a container

MethodResult
GetNumberOfSignatures(container)The number of signatures.
GetDigitalSignatureCertificate(container, index)The certificate of a signature (0-based, the signature files in name order).
GetDataFileNames(container)The names of the signed files.
ExtractDataFile(container, name)The content of a signed file (byte[]).
VerifyDigitalSignature(container)true when the container has at least one signature, all the signatures are valid and each one covers all the files of the container. A file added to the container after it was signed makes the verification fail; so does a changed file.
VerifyDigitalSignature(container, certificate)true when a valid signature that covers all the files was created with the certificate.
GetSignatures(byte[] container)A List<XadesSignatureInfo>: every signature of every signature file, with its validity, its certificate, its time-stamp, the level that it actually has (Level: B, T, LT, LTA) and the completeness of its validation data (section 8.3).

The container is a path or a byte[] in all the methods, except GetSignatures, which takes a byte[]. SignatureIsValid of XadesSignatureInfo is the validity of one signature; that every signature covers all the files of the container is checked by VerifyDigitalSignature.

AsicSignature asicSignature = new AsicSignature(LibrarySerialNumber);

int signatures = asicSignature.GetNumberOfSignatures("documents[cosigned].asice");
for (int index = 0; index < signatures; index++)
    Console.WriteLine("Signer " + index + ": " + asicSignature.GetDigitalSignatureCertificate("documents[cosigned].asice", index).Subject);

foreach (string name in asicSignature.GetDataFileNames("documents[cosigned].asice"))
    Console.WriteLine("File: " + name);

byte[] contract = asicSignature.ExtractDataFile("documents[cosigned].asice", "contract.pdf");
File.WriteAllBytes("extracted contract.pdf", contract);

Console.WriteLine("Valid: " + asicSignature.VerifyDigitalSignature("documents[cosigned].asice"));

// The level and the validation data of every signature.
foreach (XadesSignatureInfo info in asicSignature.GetSignatures(File.ReadAllBytes("documents[cosigned].asice")))
    Console.WriteLine(info.SignatureCertificate.Subject + ": valid " + info.SignatureIsValid + ", level " + info.Level
        + ", validation data complete: " + info.ValidationDataComplete);

The method verifies the integrity of the signatures and the coverage of the files; it does not decide that the signers can be trusted (section 4.5). A container that has signature files that are not XAdES (for example CAdES *.p7s files) is not verified by this class.

10.4 Raising the level of the signatures

ExtendSignature raises the XAdES signatures of a container to a higher level: B to T, LT or LTA; T to LT or LTA; LT to LTA. Only the missing parts are added (the signature time-stamp, the validation data, the archive time-stamp); a signature already at the level or above it is not changed. The signed files are not changed.

AsicSignature asicSignature = new AsicSignature(LibrarySerialNumber);
asicSignature.TimeStamping.ServerUrl = new Uri("https://ca.signfiles.com/TSAServer.aspx");

// Files (the output can be the input container).
asicSignature.ExtendSignature("documents.asice", "documents[lta].asice", XadesSignatureStandard.XadesLTA);

// In memory.
byte[] extended = asicSignature.ExtendSignature(File.ReadAllBytes("documents.asice"), XadesSignatureStandard.XadesLT);

10.5 Renewing the archive time-stamp

An XadesLTA container is protected for the long term by an archive time-stamp. AddArchiveTimestamp adds a new archive time-stamp to every XAdES-LTA signature of the container, with the validation data that is needed to validate the previous time-stamps. Call it before the certificate of the time-stamping authority of the last time-stamp expires (section 12.6). It needs TimeStamping.ServerUrl, uses LtvLevel, MaxCrlSize and AllowIncompleteValidationData, and does not need the certificate of the signers. A container without a XAdES-LTA signature, or with a XAdES-LTA signature that is not valid, throws CryptographicException; the other signatures are not changed.

LongTermArchive.GetAsicRenewalDate(container) returns the date (UTC) before which the container must be renewed: the first expiry date of the certificate chain of the time-stamping authority of the last archive time-stamp, or null when no signature has an archive time-stamp. Renew with a margin, for example 90 days before this date.

AsicSignature asicSignature = new AsicSignature(LibrarySerialNumber);

asicSignature.TimeStamping.ServerUrl = new Uri("https://ca.signfiles.com/TSAServer.aspx");
asicSignature.LtvLevel = XadesLtvLevel.IncludeCrlAndOcsp;

byte[] container = File.ReadAllBytes("documents[lta].asice");
DateTime? renewalDate = LongTermArchive.GetAsicRenewalDate(container);

if (renewalDate.HasValue && renewalDate.Value - DateTime.UtcNow < TimeSpan.FromDays(90))
    File.WriteAllBytes("documents[lta-renewed].asice", asicSignature.AddArchiveTimestamp(container));

// Or with files (the output can be the input container).
asicSignature.AddArchiveTimestamp("documents[lta].asice", "documents[lta-renewed].asice");
Keep the files together

The signatures cover the files in the container, so a container is verified as a whole. Do not repack the ZIP file with another tool (the mimetype entry must be the first one and not compressed). To use the signed files, extract them with ExtractDataFile.

10.6 Notes

11. Time-stamps

A time-stamp (RFC 3161) is a proof, signed by a time-stamping authority (TSA), that some data existed at a given time. The application sends the hash of the data to the TSA server (the data itself is never sent) and receives a signed time-stamp token. The library uses time-stamps in two ways:

11.1 Time-stamping settings

Every signature class has a property TimeStamping (TimestampSettings), and TimestampClient has one too. When the signature classes find ServerUrl set, they time-stamp the signature; when it is null (the default), they do not use the network for the time. The levels that are built on a time-stamp (PAdES-LT and LTA, CAdES-C, X Long, A, LT and LTA, XAdES-T, LT and LTA) are refused without it.

TimestampSettingsMeaning
ServerUrlThe Uri of the RFC 3161 server (HTTP or HTTPS).
UserName, PasswordHTTP basic authentication, for the servers that require it.
AuthenticationCertificateA certificate for TLS client authentication, for the servers that require it.
PolicyOid (Oid)The policy that is requested from the server. Set it only when the server requires it.
UseNonceAdd a nonce to the request, to match the response with the request. true by default.
HashAlgorithmThe hash of the request: SHA256 by default (SHA384, SHA512, SHA1). PAdES and the other long term formats should use SHA-256 or stronger. The XML signatures (XAdES, ASiC-E, Office) accept only SHA256, SHA384 and SHA512 (ArgumentException otherwise).
ServerTimeoutThe time-out of the request in milliseconds, 20000 by default.
PdfSignature pdfSignature = new PdfSignature(LibrarySerialNumber);
pdfSignature.LoadPdfDocument("source.pdf");
pdfSignature.DigitalSignatureCertificate = signingCertificate;

pdfSignature.TimeStamping.ServerUrl = new Uri("https://ca.signfiles.com/TSAServer.aspx");
pdfSignature.TimeStamping.HashAlgorithm = SignLib.HashAlgorithm.SHA256;
pdfSignature.TimeStamping.ServerTimeout = 30000;

// A server with authentication.
pdfSignature.TimeStamping.UserName = "account";
pdfSignature.TimeStamping.Password = "secret";

// Or a server that requires a TLS client certificate.
pdfSignature.TimeStamping.AuthenticationCertificate = DigitalCertificate.LoadCertificate("tsa-client.pfx", "123456");

// A policy that the server requires.
pdfSignature.TimeStamping.PolicyOid = new System.Security.Cryptography.Oid("1.3.6.1.4.1.13762.3");

File.WriteAllBytes("source[signed-T].pdf", pdfSignature.ApplyDigitalSignature());

11.2 Time-stamping a file: TimestampClient

TimestampClient returns the time-stamp of a file or of data. The property TimestampFormat chooses the format of the result:

TimestampFormatResult
DetachedTimestamp (default)The time-stamp response (RFC 3161 TimeStampResp) in a separate .tsr file. The original file is needed to verify it.
TimestampTokenOnly the time-stamp token (a CMS SignedData), without the status of the response, in a .tst file. The detached format that the EU DSS validator accepts.
EmbeddedTimestampA .tsd file (RFC 5544, Time Stamped Data) that contains the original content, its name and the time-stamp in one file.
TimestampClient timestampClient = new TimestampClient(LibrarySerialNumber);
timestampClient.TimeStamping.ServerUrl = new Uri("https://ca.signfiles.com/TSAServer.aspx");

// A .tsr file.
timestampClient.TimestampFormat = TimestampFormat.DetachedTimestamp;
File.WriteAllBytes("contract.pdf.tsr", timestampClient.ObtainTimestamp("contract.pdf"));

// A .tsd file: the file and its time-stamp.
timestampClient.TimestampFormat = TimestampFormat.EmbeddedTimestamp;
File.WriteAllBytes("contract.pdf.tsd", timestampClient.ObtainTimestamp("contract.pdf"));

// Data in memory.
byte[] timestamp = timestampClient.ObtainTimestamp(File.ReadAllBytes("contract.pdf"));

A time-stamped file proves that the file existed at the time of the time-stamp. The time-stamp of a file is not a signature of a person: it does not say who created the file.

11.3 Reading and verifying a time-stamp

TimestampInfo.GetInfoFromTsaResponse(bytes) reads a .tsr, .tst or .tsd file. new TimestampInfo(token) reads a time-stamp token. TimestampInfo.IsTsaReponseFileValid(originalFile, timestamp) verifies a time-stamp file against the original file and returns true, or throws CryptographicException when the file was changed, the time-stamp was altered, the certificate of the authority is not a time-stamping certificate (extended key usage id-kp-timeStamping) or was not valid at the time of the time-stamp, or the time-stamp uses MD5. For a .tsd file that contains the original content, originalFile can be null; when it is set, it must be identical with the embedded content. The same TimestampInfo is the property TimestampInfo of the signatures that have a time-stamp (PdfSignatureInfo, CadesSignatureInfo).

TimestampInfoMeaning
SignatureTimeThe time of the time-stamp (UTC).
AccuracyThe accuracy of the time (Seconds, Milliseconds, Microseconds; a value is null when the server does not set it).
IsTimestampAlteredtrue when the signature of the time-stamp token is not valid: the token was changed.
TsaCertificate, TsaServerNameThe certificate of the time-stamping authority (when it is in the token) and its name.
HashAlgorithm (Oid), OriginalDataHashThe algorithm and the value of the hash that was time-stamped (the message imprint).
Policy (Oid), SerialNumber, NonceThe policy of the server, the serial number of the time-stamp and the nonce of the request.
IsQualifiedTimestamptrue when the token declares itself a qualified electronic time-stamp (ETSI EN 319 422). The qualified status is given by the EU trusted lists: a qualified server can issue time-stamps without this statement.
TimestampedDataContent, TimestampedDataFileNameFor a .tsd file: the embedded original content and its name (null when it is not embedded).
TimestampTokenThe encoded time-stamp token.
byte[] timestampFile = File.ReadAllBytes("contract.pdf.tsr");

TimestampInfo info = TimestampInfo.GetInfoFromTsaResponse(timestampFile);
Console.WriteLine("Time: " + info.SignatureTime.ToLocalTime());
Console.WriteLine("Authority: " + (info.TsaCertificate != null ? info.TsaCertificate.Subject : "(not in the token)") + ", hash " + info.HashAlgorithm.FriendlyName);
Console.WriteLine("Altered: " + info.IsTimestampAltered + ", qualified: " + info.IsQualifiedTimestamp);

try
{
    TimestampInfo.IsTsaReponseFileValid(File.ReadAllBytes("contract.pdf"), timestampFile);
    Console.WriteLine("The time-stamp matches the file.");
}
catch (CryptographicException ex)
{
    Console.WriteLine("The verification failed: " + ex.Message);       // the file or the time-stamp was changed
}

The checks above verify the time-stamp token, its link with the data and the time-stamping certificate itself. As for the signatures, the decision that the time-stamping authority can be trusted is yours: check that the chain of its certificate ends in a root that you trust (or in the EU trusted list for qualified time-stamps), and its revocation status (section 5.4).

11.4 Time-stamps of the signatures

FormatWhat the time-stamp coversHow to read it
PDFThe signature (signature time-stamp) and, in PAdES-LTA, the whole document (document time-stamp, ApplyTimestampSignature; renewed with AddArchiveTimestamp).PdfSignatureInfo.SignatureIsTimestamped, TimestampInfo; a document time-stamp is a PdfSignatureInfo with SignatureType.TimestampSignature.
CAdESThe signature value (CAdES-T); the references (CAdES-X Long); the signature and its validation data (CAdES-A and CAdES-B-LTA, archive time-stamp v3; renewed with CadesSignature.AddArchiveTimestamp).CadesSignatureInfo.SignatureIsTimestamped, TimestampInfo.
XAdES, ASiC-EThe signature value (SignatureTimeStamp); the archive time-stamps (xades141:ArchiveTimeStamp) of the LTA level.XadesSignatureInfo.SignatureIsTimestamped, TimestampInfo, ArchiveTimestamps (XadesSignature.GetSignatures, AsicSignature.GetSignatures).
OfficeThe signature value (XAdES-T).OfficeSignatureInfo.HasTimestamp, TimestampTime.

How the time-stamps make a signature last, and how to renew them, is in section 12.

12. Long term validation and archiving

A signature has to be validated when it is read, maybe years after it was made, and by then the certificate of the signer has expired, the certification authority may no longer publish the revocation information, and the algorithms of the time may be weak. The long term levels of the signatures (B-T, B-LT, B-LTA) keep the evidence that is needed to validate the signature as of the time when it was created. This chapter explains what the library embeds in the signatures, how to create the levels in every format, how to read the level of a signature, how the revocation data is obtained and cached, and how to renew the time-stamps of an archive.

12.1 What each level adds

time signingB-B: signature + certificate + time-stampB-T: proof of the time + validation dataB-LT: certificates, CRL, OCSP + archive time-stampB-LTA: protects all of the above renewala new archive time-stamp the evidence is complete when the signature is created (B-LT) repeat before the last time-stamp expires
The long term evidence. A validator uses the embedded data and the time-stamps, and does not depend on the servers of the certification authority.

12.2 Creating the levels

FormatB-TB-LTB-LTA
PDFTimeStamping.ServerUrlSignatureStandard = PadesLT, PadesLtvLevelSignatureStandard = PadesLTA
CAdESSignatureStandard = CadesTSignatureStandard = CadesLT (also CadesC, CadesXL), LtvLevelSignatureStandard = CadesLTA (also CadesA)
XAdESXadesTXadesLT, LtvLevelXadesLTA
ASiC-EXadesTXadesLT, LtvLevelXadesLTA
OfficeXadesTXadesLT, LtvLevelnot supported

In every case TimeStamping.ServerUrl must be set for T, LT and LTA (section 11.1). A B-LT or B-LTA signature is created only with its complete validation data; otherwise the signing throws ValidationDataException (section 12.3), and the level of a signed document is read with Level (section 12.4). Examples: section 6.9 (PDF), section 7.2 (CAdES), section 8.2 (XAdES), section 10.1 (ASiC-E), section 9.1 (Office).

12.3 The validation data

When it signs at a long term level, the library collects the revocation information from the addresses that are written in the certificates (the CRL distribution points and the OCSP responders of the Authority Information Access extension). It embeds the data of the whole chain of the signing certificate and of the chain of the time-stamping authority of the signature time-stamp. Every address of a certificate is tried in turn, and an OCSP response or a CRL is embedded only when it can be trusted: signed by the issuer of the certificate (or by a delegated OCSP responder) and current. The selection of the revocation data is the same enumeration, with the same values, in the formats:

Value (PadesLtvLevel, XadesLtvLevel, CadesLtvLevel)Embedded data
IncludeOcspOnlyThe default of every format. For the signing certificate and the certificate of the time-stamping authority: the OCSP response, and the CRL only when the OCSP response is not available. For the CA certificates: the CRL, and the OCSP response only when the CRL is not available. The smallest result.
IncludeCrlAndOcspThe OCSP response and the CRL of every certificate of the chains.
IncludeCrlThe CRLs of the chains.
NoneNo revocation data. Not accepted for the long term levels (InvalidOperationException), unless AllowIncompleteValidationData is set.

For CAdES the property is CadesSignature.LtvLevel; it applies to the levels CadesC, CadesXL, CadesA, CadesLT and CadesLTA (section 7.3). For XAdES, ASiC-E and Office it is LtvLevel, for PDF PadesLtvLevel.

The validation data must be complete. A root (self-signed) certificate needs no revocation data; every other certificate of the two chains needs an OCSP response or a CRL. When one cannot be obtained, the signing throws ValidationDataException before the document is written: a signature without this data would not be a B-LT signature (section 12.4). The usual causes:

A revoked certificate of the signer or of the time-stamping authority stops the signing with CertificateRevokedException, always. An OCSP status unknown is not a revocation: the library then uses the CRL. The downloads use NetworkSettings.RevocationTimeout (section 4.10).

The size of the signature grows with the validation data: the CRLs of some certification authorities have megabytes. PAdES-LT and PAdES-LTA keep the data in the document security store (/DSS) of the PDF document, one copy of each certificate, OCSP response and CRL.

12.4 The level of a signature

The signature information classes report the level that a signature really has, determined from what it contains:

PropertyMeaning
LevelA SignatureLevel (namespace SignLib): B, T, LT, LTA, or None for a signature that is not an AdES signature (a PKCS#7 signature without the signing-certificate attribute, XMLDSig without the XAdES properties, a document time-stamp) or that is not valid.
ValidationDataCompletetrue when the signature contains an OCSP response or a CRL for every certificate (except the root) of the chains of the signer and of the time-stamping authority of the signature time-stamp, valid at the time of the time-stamp.
MissingValidationDataThe certificates without validation data (empty when ValidationDataComplete is true): MissingValidationData objects with Subject, Thumbprint, IsTimestampAuthority and Reason.

They exist on PdfSignatureInfo (PdfSignature.DocumentProperties.DigitalSignatures), CadesSignatureInfo (every signer of CadesVerify.Signatures; CadesVerify.Level is the lowest level of the signers), XadesSignatureInfo (XadesSignature.GetSignatures, AsicSignature.GetSignatures) and OfficeSignatureInfo (OfficeSignature.GetSignatures; B, T or LT). The rules: LT needs a time-stamp and the complete validation data, valid at the time of the time-stamp; LTA needs, in addition, a document time-stamp over a revision that contains the document security store (PDF), or an archive time-stamp (CAdES, XAdES). In the validation runs of the library with the EU DSS validator, the level reported by SignLib is the level reported by DSS for every baseline signature.

PdfSignature verifier = new PdfSignature(LibrarySerialNumber);
verifier.LoadPdfDocument("source[lta].pdf");

foreach (PdfSignatureInfo info in verifier.DocumentProperties.DigitalSignatures)
{
    Console.WriteLine(info.SignatureName + ": " + info.Level + ", validation data complete: " + info.ValidationDataComplete);

    foreach (MissingValidationData missing in info.MissingValidationData)
        Console.WriteLine("  missing: " + missing);
}

// CAdES: the lowest level of the signers, and the level of every signer.
CadesVerify cades = new CadesVerify("contract.pdf.p7m", LibrarySerialNumber);
Console.WriteLine("CAdES level: " + cades.Level);

// XAdES and ASiC-E.
XadesSignature xades = new XadesSignature(LibrarySerialNumber);
foreach (XadesSignatureInfo info in xades.GetSignatures("invoice[lta].xml"))
    Console.WriteLine("XAdES level: " + info.Level);

Incomplete validation data

ValidationDataException (namespace SignLib.Certificates, derived from CryptographicException) is thrown by the long term levels (PAdES-LT/LTA, CAdES-LT/LTA/C/XL/A, XAdES-LT/LTA, ASiC-E, Office XAdES-LT), by the archive renewal and by the extension of a signature, when the revocation data of a certificate cannot be obtained. No document is produced. Its MissingData lists the certificates and the reasons (no OCSP or CRL address, the OCSP responder did not answer validly, the CRL is larger than MaxCrlSize, the issuer was not found...). Retry later, or fix the cause.

The property AllowIncompleteValidationData of PdfSignature, CadesSignature, XadesSignature, AsicSignature and OfficeSignature (default false) creates the signature anyway, with the data that could be obtained; it also accepts a long term level with the revocation data set to None, and a PAdES-LT signature without a time-stamping server. Such a signature is not a B-LT signature: its Level is lower (usually T) and MissingValidationData says what is missing. A revoked certificate is reported even with this property (CertificateRevokedException).

CadesSignature cades = new CadesSignature(LibrarySerialNumber);
cades.DigitalSignatureCertificate = signingCertificate;
cades.SignatureStandard = CadesSignatureStandard.CadesLT;
cades.TimeStamping.ServerUrl = new Uri("https://ca.signfiles.com/TSAServer.aspx");

try
{
    File.WriteAllBytes("contract.pdf.p7m", cades.ApplyDigitalSignature("contract.pdf"));
}
catch (ValidationDataException ex)
{
    foreach (MissingValidationData missing in ex.MissingData)
        Console.WriteLine((missing.IsTimestampAuthority ? "TSA " : "") + missing.Subject + ": " + missing.Reason);

    // Retry later; or, when a lower level is acceptable, sign with the data that is available:
    cades.AllowIncompleteValidationData = true;
    File.WriteAllBytes("contract.pdf.p7m", cades.ApplyDigitalSignature("contract.pdf"));
}

12.5 The revocation cache and the revocation sources

The OCSP responses and the CRLs downloaded for the long term signatures are kept in memory by the static class RevocationCache (namespace SignLib.Certificates), shared by all the signature classes of the process: the documents signed one after another, or in parallel, with the same certificate reuse the data instead of downloading it for every document, and the signatures created in parallel for the same certificate download it once. The cache is used only when signing: the verification of signatures and certificates (CertificateValidator, VerifyDigitalCertificate) always gets current data. Nothing is written to the disk.

The OCSP responses of a long term signature are issued after its time-stamp. The revocation data shows the status of a certificate at the time of the signature (its best-signature-time, the time of the signature time-stamp: ETSI EN 319 102-1), so the OCSP responses embedded in a long term signature (PAdES-LT/LTA, CAdES-LT/LTA, C, X Long and A, XAdES-LT/LTA, ASiC-E, Office XAdES-LT), for the certificate chain of the signer and of the time-stamping authority, are requested after the time-stamp: a cached response issued earlier is not used. This is also what DSS does when it augments a signature, and some validators (eParaksts, for example) reject a signature whose OCSP response is older than its time-stamp. When no newer response can be obtained (the responder does not answer, UseNetwork is false, or the responder returns pre-produced responses), the best available one is used: cached, added or provided. The CRLs, and the OCSP responses of Prefetch and of the checks made before signing, are reused as described below.

MemberDefaultMeaning
EnabledtrueThe revocation data is cached. Setting it to false also clears the cache.
OcspMaxAge5 minutesThe maximum time an OCSP response is reused after it was downloaded. A response is never reused when it is valid (its nextUpdate) for less than one more minute. TimeSpan.Zero downloads a new response for every signature.
CrlMaxAge1 hourThe maximum time a CRL is reused after it was downloaded, while it is valid for at least one more minute.
MaxCrlCacheSize100 MBThe maximum total size of the cached CRLs; the least recently used ones are removed.
FailureRetention60 secondsThe time a failed download (a server that does not answer, an invalid response) is remembered: the next documents do not wait again for the time-out of the same server. TimeSpan.Zero retries for every signature.
ProvidernullA source of revocation data of the application (IRevocationDataProvider), asked before the network.
UseNetworktrueThe OCSP responders and the CRL distribution points are contacted. With false, only the data of Provider and the data added with AddCrl and AddOcspResponse are used (a server without Internet access).
AddCrl(byte[]), AddOcspResponse(byte[])Add a CRL (DER or PEM) or an OCSP response (DER OCSPResponse or BasicOCSPResponse) obtained by the application. They are used while they are current and kept until Clear(); ArgumentException when the data is not a CRL or a successful OCSP response.
Prefetch(certificate, timestamping)Downloads into the cache the revocation data of the chain of a signing certificate and, when the TimestampSettings are given, of the time-stamping authority (a time-stamp is requested to learn its certificate), before the first document of a batch. Returns the MissingValidationData list (empty when everything is available); throws CertificateRevokedException for a revoked certificate. The long term signatures still request new OCSP responses after their time-stamp; the prefetched ones are used when no newer one can be obtained.
Clear()Removes the cached responses, CRLs and failures, and the added data.

The data of every source (the network, Provider, AddCrl, AddOcspResponse) is validated in the same way: signed by the issuer of the certificate or by a delegated OCSP responder, current, for the right certificate. The revocation policy of the library is the same in all the formats: the default IncludeOcspOnly asks OCSP for the signer and the time-stamping authority and the CRL for the CA certificates (section 12.3); a revoked certificate always stops the signing; a missing data stops a long term signature (section 12.4).

// Once, before a batch: the data is downloaded now, and a problem is reported before the first document.
TimestampSettings timestamping = new TimestampSettings();
timestamping.ServerUrl = new Uri("https://ca.signfiles.com/TSAServer.aspx");

IReadOnlyList<MissingValidationData> missing = RevocationCache.Prefetch(signingCertificate, timestamping);
if (missing.Count > 0)
    Console.WriteLine("The long term signatures will fail: " + string.Join("; ", missing.Select(m => m.ToString())));

A server without Internet access gets the data from the application, with an IRevocationDataProvider. Its two methods return the DER data, or null when it is not available (then the network is used, unless UseNetwork is false):

// Revocation data from an internal mirror (a folder, a database, an internal web server).
public class MirrorRevocationProvider : IRevocationDataProvider
{
    public byte[] GetOcspResponse(X509Certificate2 certificate, X509Certificate2 issuer)
    {
        return null;    // no OCSP mirror: the CRL is used
    }

    public byte[] GetCrl(X509Certificate2 certificate, string url)
    {
        // The CRL published at the address written in the certificate, copied to the mirror.
        string file = Path.Combine(@"D:\crl-mirror", Path.GetFileName(new Uri(url).AbsolutePath));
        return File.Exists(file) ? File.ReadAllBytes(file) : null;
    }
}
RevocationCache.Provider = new MirrorRevocationProvider();
RevocationCache.UseNetwork = false;     // only the mirror and the added data

12.6 Renewing the time-stamps of an archive

An archive time-stamp is valid while the certificate of the time-stamping authority is valid and while its algorithms are strong. Before one of them ends, a new archive time-stamp is added over the whole signature and over the validation data of the previous time-stamp; the protection continues for another period. The operation is repeated for the whole archiving period. It does not need the certificates or the keys of the signers.

FormatHow to renewRenewal date
PDFPdfSignature.AddArchiveTimestamp() (or AddArchiveTimestamp(Stream output)) adds to the document security store, in one revision, the validation data of all the signatures and document time-stamps (including the time-stamping authority of the last document time-stamp), then a new document time-stamp. It uses PadesLtvLevel, AllowIncompleteValidationData and TimeStamping, and refuses a document with a signature that is not valid. (ApplyTimestampSignature() only adds a document time-stamp, without the validation data.)LongTermArchive.GetPdfRenewalDate(signatures)
CAdESCadesSignature.AddArchiveTimestamp(byte[] signature, byte[] detachedContent = null) adds the validation data of the time-stamping authority of the last archive time-stamp of every CAdES-LTA signer, then a new archive-time-stamp-v3, which covers the previous ones. The signed document is needed for a detached signature. It uses LtvLevel, MaxCrlSize, AllowIncompleteValidationData and TimeStamping; InvalidOperationException when the signature has no CAdES-LTA signer.LongTermArchive.GetCadesRenewalDate(byte[])
XAdESXadesSignature.AddArchiveTimestamp(inputFile, outputFile) for enveloped signatures, AddArchiveTimestamp(signatureFile, outputFile, originalFile) for detached signatures (section 8.5).LongTermArchive.GetXadesRenewalDate(string)
ASiC-EAsicSignature.AddArchiveTimestamp(...) adds a new archive time-stamp to every XAdES-LTA signature of the container (section 10.5).LongTermArchive.GetAsicRenewalDate(byte[])

The XAdES and ASiC-E signatures of a lower level (B, T, LT) are raised to LT or LTA with XadesSignature.ExtendSignature and AsicSignature.ExtendSignature, which add only the missing time-stamp, validation data and archive time-stamp (section 8.4, section 10.4). Before a new archive time-stamp, the library adds the certificates and the current revocation data that are needed to validate the previous time-stamps (for XAdES, xades141:TimeStampValidationData). All the renewal methods need TimeStamping.ServerUrl, and they throw ValidationDataException or CertificateRevokedException as the signing does (section 12.4).

The decision when to renew is the policy of your archive. The methods of the static class LongTermArchive (namespace SignLib) return the first expiry date (UTC) of the certificate chain of the time-stamping authority of the last archive (or document) time-stamp, or null when there is no such time-stamp. Renew with a margin before this date (at least 90 days, for example), and immediately when an algorithm in use is no longer acceptable. A scheduled task reads every archived document, applies the rule and renews the documents that need it:

public static class ArchiveRenewal
{
    private static readonly TimeSpan RenewalMargin = TimeSpan.FromDays(90);

    // True when the chain of the TSA of the last document time-stamp expires in less than the margin
    // (or the document has no document time-stamp).
    public static bool IsRenewalNeeded(byte[] signedPdf, string serialNumber)
    {
        PdfSignature pdfSignature = new PdfSignature(serialNumber);
        pdfSignature.LoadPdfDocument(signedPdf);

        DateTime? renewalDate = LongTermArchive.GetPdfRenewalDate(pdfSignature.DocumentProperties.DigitalSignatures);
        return renewalDate == null || renewalDate.Value - DateTime.UtcNow < RenewalMargin;
    }

    // Adds the validation data of the previous time-stamps and a new document time-stamp: no signing certificate is needed.
    public static byte[] Renew(byte[] signedPdf, string serialNumber, Uri timestampServer)
    {
        PdfSignature pdfSignature = new PdfSignature(serialNumber);
        pdfSignature.LoadPdfDocument(signedPdf);
        pdfSignature.TimeStamping.ServerUrl = timestampServer;

        return pdfSignature.AddArchiveTimestamp();
    }
}

The same for CAdES, XAdES and ASiC-E:

Uri timestampServer = new Uri("https://ca.signfiles.com/TSAServer.aspx");
TimeSpan margin = TimeSpan.FromDays(90);

// A CAdES-LTA signature (attached; for a detached signature give the signed document as the second parameter).
byte[] p7m = File.ReadAllBytes("contract.pdf.p7m");
DateTime? cadesDate = LongTermArchive.GetCadesRenewalDate(p7m);
if (cadesDate != null && cadesDate.Value - DateTime.UtcNow < margin)
{
    CadesSignature cades = new CadesSignature(LibrarySerialNumber);
    cades.TimeStamping.ServerUrl = timestampServer;
    File.WriteAllBytes("contract.pdf.p7m", cades.AddArchiveTimestamp(p7m));
}

// A XAdES-LTA XML document with an enveloped signature.
DateTime? xadesDate = LongTermArchive.GetXadesRenewalDate("invoice[lta].xml");
if (xadesDate != null && xadesDate.Value - DateTime.UtcNow < margin)
{
    XadesSignature xades = new XadesSignature(LibrarySerialNumber);
    xades.TimeStamping.ServerUrl = timestampServer;
    xades.AddArchiveTimestamp("invoice[lta].xml", "invoice[lta].xml");
}

// An ASiC-E container.
byte[] container = File.ReadAllBytes("documents[lta].asice");
DateTime? asicDate = LongTermArchive.GetAsicRenewalDate(container);
if (asicDate != null && asicDate.Value - DateTime.UtcNow < margin)
{
    AsicSignature asic = new AsicSignature(LibrarySerialNumber);
    asic.TimeStamping.ServerUrl = timestampServer;
    File.WriteAllBytes("documents[lta].asice", asic.AddArchiveTimestamp(container));
}

The complete sample Timestamp Renewal (section 16) renews the time-stamps of a PDF document, of an ASiC-E container and of an XAdES document.

12.7 Recommendations

13. External keys: tokens, HSMs and remote signing

In many deployments the private key cannot be loaded in the process of your application: it is on a smart card or a USB token, in a hardware security module (HSM), in a cloud key vault or in a remote signing service, and it never leaves that device. The library supports these keys with two mechanisms:

13.1 The signature provider

The interface has one method:

public interface IExternalSignature
{
    byte[] ApplySignature(byte[] message, Oid hashAlgorithm);
}

The certificate that you give to the signature object needs only the public part. The key stays in the device:

// A provider and the public certificate of the signer.
IExternalSignature provider = new CertificateKeyExternalSignature(signingCertificate);   // see the example below
X509Certificate2 publicCertificate = new X509Certificate2(File.ReadAllBytes("signer.cer"));

PdfSignature pdfSignature = new PdfSignature(LibrarySerialNumber);
pdfSignature.LoadPdfDocument("source.pdf");
pdfSignature.DigitalSignatureCertificate = publicCertificate;        // no private key

// Bind the provider to the NEXT signature of this thread. The library releases it at the end of the operation.
DigitalCertificate.UseExternalSignatureProvider = provider;

File.WriteAllBytes("source[signed].pdf", pdfSignature.ApplyDigitalSignature());

The same property is used with the other classes: set it, then call CadesSignature.ApplyDigitalSignature, XmlSignature.ApplyDigitalSignature, XadesSignature.ApplyDigitalSignature, OfficeSignature.ApplyDigitalSignature, or the methods of AsicSignature that sign.

Rules of the provider

Rules of the provider
  • Set it before every signature. DigitalCertificate.UseExternalSignatureProvider applies to the next signing operation of the current thread and is released when the operation ends, also when it fails. To sign two documents, set it two times.
  • It is thread-local. In a parallel loop set it inside the body, on the thread that signs. Do not share a provider object that is not thread-safe (a PKCS#11 session, for example) between threads.
  • The key must match the certificate. For the XML signatures (XMLDSig, XAdES, ASiC-E, Office) and for FinalizeExternalSignature (section 13.5) the library verifies the value with the public key of the certificate before it uses it, and refuses a wrong value with CryptographicException. For the PDF and CAdES signatures created with a provider, a value that was made with another key gives an invalid signature: verify the first signatures of a new provider.
  • Report errors as exceptions. The library reports an exception of the provider as a CryptographicException (Error on creating digital signature: ...) whose InnerException is the exception of the provider. Close the sessions of the device in a finally block.
  • Do not keep the PIN in the code. Read it from a protected source when the application starts.

13.2 A provider with a .NET key

The simplest provider uses a key that .NET can use (a key that is not exportable, a CNG key, a key that another process holds). It shows what the method has to do and it is a model for the others:

public class CertificateKeyExternalSignature : IExternalSignature
{
    private readonly X509Certificate2 _certificateWithPrivateKey;

    public CertificateKeyExternalSignature(X509Certificate2 certificateWithPrivateKey)
    {
        _certificateWithPrivateKey = certificateWithPrivateKey;
    }

    public byte[] ApplySignature(byte[] message, Oid hashAlgorithm)
    {
        HashAlgorithmName hash = GetHashAlgorithmName(hashAlgorithm.Value);

        // RSA: PKCS#1 v1.5 over the hash of the message.
        using (RSA rsa = _certificateWithPrivateKey.GetRSAPrivateKey())
        {
            if (rsa != null)
                return rsa.SignData(message, hash, RSASignaturePadding.Pkcs1);
        }

        // ECDSA: the raw value r || s. The library converts it to the form of the signature format.
        using (ECDsa ecdsa = _certificateWithPrivateKey.GetECDsaPrivateKey())
        {
            if (ecdsa != null)
                return ecdsa.SignData(message, hash);
        }

        throw new CryptographicException("The private key of the certificate was not found or its algorithm is not supported.");
    }

    private static HashAlgorithmName GetHashAlgorithmName(string oid)
    {
        switch (oid)
        {
            case "1.3.14.3.2.26": return HashAlgorithmName.SHA1;
            case "2.16.840.1.101.3.4.2.1": return HashAlgorithmName.SHA256;
            case "2.16.840.1.101.3.4.2.2": return HashAlgorithmName.SHA384;
            case "2.16.840.1.101.3.4.2.3": return HashAlgorithmName.SHA512;
            default: throw new NotSupportedException("The hash algorithm " + oid + " is not supported.");
        }
    }
}

13.3 PKCS#11 tokens and HSMs

PKCS#11 (Cryptoki) is the standard programming interface of smart cards, USB tokens and HSMs. Every manufacturer supplies a module (a DLL on Windows, a .so file on Linux) that implements it, and the provider calls the module to sign with the key that stays on the device. This works on any operating system, without the Windows smart card minidriver and without the PIN window of Windows, and it is the way for services and servers.

DeviceTypical PKCS#11 module
SafeNet / Thales eTokenC:\Windows\System32\eTPKCS11.dll
OpenSC (many smart cards)C:\Program Files\OpenSC Project\OpenSC\pkcs11\opensc-pkcs11.dll
Thales Luna HSMC:\Program Files\SafeNet\LunaClient\cryptoki.dll

A 64-bit process needs the 64-bit module and a 32-bit process the 32-bit one. The samples PDF Digital Signature with PKCS11 Smart Card, P7M P7S CAdES Digital Signature with PKCS11 Smart Card and PDF Digital Signature with PKCS11 Driver for HSM contain the class Pkcs11ExternalSignature, a complete provider written with the library Pkcs11Interop (NuGet Pkcs11Interop): copy it into your project. It does what a provider has to do:

  1. loads the module, finds the slot of the token (SlotIndex: the index among the slots that have a token) and opens a session with the PIN;
  2. finds the certificates that have a private key on the token (GetCertificatesFromToken()), and the private key of the signing certificate (the certificate and its key share the attribute CKA_ID);
  3. in ApplySignature: for RSA, signs with the mechanism that hashes and signs (CKM_SHA256_RSA_PKCS and the like), and, for tokens that do not have it, hashes the data and signs the DigestInfo with CKM_RSA_PKCS; for ECDSA, hashes the data and signs the hash with CKM_ECDSA (the result is the raw r || s).
// Excerpt of the samples that use a token. The constants are set by the application; the PIN is read from a protected source.
private const string Pkcs11LibraryPath = @"C:\Windows\System32\eTPKCS11.dll";
private const string TokenPin = "";              // do not store a PIN in the source code of a real application
private const int SlotIndex = 0;                 // the index of the token among the slots that have a token present

// The thumbprint of the signing certificate. When it is set, the certificate is found on the token without a window
// (a service); when it is empty, the user selects the certificate when the token has several.
private const string CertificateThumbprint = "";

Pkcs11ExternalSignature externalSignature = new Pkcs11ExternalSignature(Pkcs11LibraryPath, TokenPin, SlotIndex);

externalSignature.SigningCertificate = SelectCertificate(externalSignature.GetCertificatesFromToken());   // by thumbprint or by window

PdfSignature pdfSignature = new PdfSignature(LibrarySerialNumber);
pdfSignature.LoadPdfDocument("source.pdf");
pdfSignature.DigitalSignatureCertificate = externalSignature.SigningCertificate;        // the public part

DigitalCertificate.UseExternalSignatureProvider = externalSignature;                   // before every signature
File.WriteAllBytes("source[signed].pdf", pdfSignature.ApplyDigitalSignature());

13.4 ECDSA signature values

The ECDSA signature value has two encodings. CMS (PDF, CAdES) requires the DER form SEQUENCE { INTEGER r, INTEGER s } (RFC 5753); XMLDSig (XML, XAdES, ASiC-E) requires the raw form r || s (RFC 4051). PKCS#11 modules, HSMs and cloud services usually return the raw form, and .NET's ECDsa.SignData too. A provider returns either form: the library accepts both and writes the form that the signature format needs. It does not change the signatures of RSA keys.

13.5 Two-phase PDF signing

When the signer cannot sign during the call, the PDF signature is created in three steps, which can be in different processes and at different times:

Application / server (SignLib) Signer (device, service, person) 1. PrepareExternalSignaturePendingExternalSignature DataToSign + DigestAlgorithmOid 2. Signs the datawith its private key signature value 3. FinalizeExternalSignaturethe signed PDF
The signer receives only the data to sign (the hash of the document inside the signed attributes), never the document.
  1. PdfSignature.PrepareExternalSignature(fieldName) prepares the document exactly as ApplyDigitalSignature does (the signature field, the appearance, the space for the signature) and computes the data to sign. No private key is used. The result is a PendingExternalSignature: DataToSign (the DER signed attributes), DigestAlgorithmOid and everything that is needed to complete the signature. Pass null as the field name for a new field. The prepared document is kept whole in PendingExternalSignature.PendingDocument: a document loaded from a stream is read into memory in this step.
  2. The signer hashes DataToSign with DigestAlgorithmOid and signs the hash. The value is the same that IExternalSignature.ApplySignature returns.
  3. PdfSignature.FinalizeExternalSignature(pending, signatureValue) inserts the signature in the prepared document and returns the signed PDF. No private key is needed. If TimeStamping.ServerUrl is set on the object of this step, the signature is time-stamped; for PAdES-LT and PAdES-LTA the validation data and the document time-stamp are completed in this step. Before it uses them, the method checks the prepared signature (a PendingExternalSignature that is incomplete or does not match its document throws ArgumentException) and verifies the signature value with the public key of the certificate (a value that was not made over DataToSign with the key of the certificate throws CryptographicException, instead of producing an invalid PDF).

The signature must be made over the signature settings that you choose in step 1 (the standard, the hash, the appearance): they are fixed by PrepareExternalSignature. For PAdES-LT and PAdES-LTA, set TimeStamping.ServerUrl on the objects of both steps: step 1 refuses a long term signature without a time-stamping server (InvalidOperationException), and step 3 time-stamps the signature and the document. PendingExternalSignature has no private data, and it can be serialized (for example as JSON: the byte arrays are written as Base64 text) and stored between the steps. Do not use BinaryFormatter.

// Step 1: prepare. Only the public certificate of the signer is needed.
PdfSignature prepare = new PdfSignature(LibrarySerialNumber);
prepare.LoadPdfDocument("source.pdf");
prepare.DigitalSignatureCertificate = new X509Certificate2(File.ReadAllBytes("signer.cer"));
prepare.SignatureStandard = PdfSignatureStandard.Pades;
prepare.SigningReason = "I approve this document";
prepare.SignaturePosition = SignaturePosition.TopLeft;

PendingExternalSignature pending = prepare.PrepareExternalSignature(null);
Console.WriteLine("Sign " + pending.DataToSign.Length + " bytes with the hash algorithm " + pending.DigestAlgorithmOid);

// Step 2: the signer signs the data. Here: a certificate with a private key, as a stand-in for a remote signer.
X509Certificate2 signerWithKey = DigitalCertificate.LoadCertificate("cert.pfx", "123456");
byte[] signatureValue = new CertificateKeyExternalSignature(signerWithKey)
    .ApplySignature(pending.DataToSign, new System.Security.Cryptography.Oid(pending.DigestAlgorithmOid));

// Step 3: finalize (the same or another process, later).
PdfSignature finalize = new PdfSignature(LibrarySerialNumber);
byte[] signedPdf = finalize.FinalizeExternalSignature(pending, signatureValue);

File.WriteAllBytes("source[signed].pdf", signedPdf);
Where to keep the prepared signature

If the signer is a person or a remote service that you do not control, keep PendingExternalSignature on your server and give the signer only an identifier and the data to sign: the signer cannot change the document that you finalize. The sample PDF Signing Web Service (section 15.5) is a complete client and server pair built this way. When the signer is the one who owns the document, serializing the pending signature (JSON) and sending it with the data is also possible.

13.6 Cloud key vaults and remote services

The pattern is the same for every service: the certificate (public) is read from the service, and the provider sends the data to the sign operation of the service.

// A provider for a service that signs a digest: the provider hashes the message, the service signs the hash.
public class DigestSigningServiceSignature : IExternalSignature
{
    private readonly Func<byte[], string, byte[]> _signDigest;     // the call of your service: (digest, hashAlgorithmOid) -> the signature value

    public DigestSigningServiceSignature(Func<byte[], string, byte[]> signDigest)
    {
        _signDigest = signDigest;
    }

    public byte[] ApplySignature(byte[] message, Oid hashAlgorithm)
    {
        byte[] digest;

        switch (hashAlgorithm.Value)
        {
            case "2.16.840.1.101.3.4.2.1": digest = SHA256.Create().ComputeHash(message); break;
            case "2.16.840.1.101.3.4.2.2": digest = SHA384.Create().ComputeHash(message); break;
            case "2.16.840.1.101.3.4.2.3": digest = SHA512.Create().ComputeHash(message); break;
            default: throw new NotSupportedException("The hash algorithm " + hashAlgorithm.Value + " is not supported.");
        }

        return _signDigest(digest, hashAlgorithm.Value);
    }
}

14. eIDAS signatures

The eIDAS Regulation (EU) No 910/2014 on electronic identification and trust services (as amended) defines the legal effect of electronic signatures in the European Union. This chapter explains, technically, what the library gives to an application that must create or check eIDAS signatures. It is a simplified explanation and it is not legal advice.

14.1 The levels and what produces them

LevelWhat it needsThe library
Electronic signatureAny data in electronic form that is attached to other data and used to sign.Any signature that the library creates.
Advanced electronic signature (AdES)It is uniquely linked to the signatory, it identifies the signatory, it is created with data that the signatory can use under his sole control, and it detects any later change of the data. In practice: a signature in a standard format (PAdES, XAdES, CAdES) made with a certificate issued to the signatory.The formats PAdES (PdfSignature), CAdES (CadesSignature), XAdES (XadesSignature) and the container ASiC-E (AsicSignature), with the baseline levels B-B, B-T, B-LT, B-LTA. The level of a signature is read with Level (SignatureLevel B, T, LT, LTA, section 12.4).
Qualified electronic signature (QES)An advanced signature, created by a qualified signature creation device (QSCD), and based on a qualified certificate issued by a qualified trust service provider. It has the legal effect of a handwritten signature in the member states.The library signs with the key that is in the QSCD (a token or an HSM, through the Windows driver or PKCS#11, or a remote qualified signing service, section 13). It does not make a signature qualified: the certificate and the device do.
Qualified electronic sealThe same for a legal person (a certificate of an organization).The same formats; the certificate is a seal certificate.
Qualified time-stampA time-stamp issued by a qualified trust service provider.TimestampSettings with the server of a qualified provider; TimestampInfo.IsQualifiedTimestamp reads the statement of the token.

A signature is advanced or qualified because of the certificate (who issued it and with which identification), the device (where the key is) and the validation (that the certificate was qualified when the signature was made, according to the trusted lists). The library creates the signature in the right format and gives you the data to validate it; the legal level is a property of the whole.

14.2 Which format for what

DocumentFormatClass
PDF documentPAdES (B-B, B-LT, B-LTA); the classic PKCS#7 PDF signature (Default) is not a PAdES formatPdfSignature
A file of any typeCAdES, attached (.p7m) or detached (.p7s); or XAdES detachedCadesSignature, XadesSignature
An XML document (invoice, e-government message)XAdES enveloped (B-B, B-T, B-LT, B-LTA)XadesSignature
Several files, signed togetherASiC-E container with XAdESAsicSignature
Office documentPackage signature with XAdES (the format of Microsoft Office)OfficeSignature

A national or sectorial regulation can require an explicit signature policy or a given level: set the policy with SetSignaturePolicyInformation (section 6.14) and use the level that it asks, usually B-LT or B-LTA with a time-stamp from a qualified provider.

14.3 Creating a qualified signature

  1. The signatory has a qualified certificate on a QSCD: a token or a smart card from a qualified trust service provider (or a remote QSCD service). The qualified certificates have the qcStatements extension with QcCompliance and QcSSCD.
  2. The application gets the certificate: from the Windows store (the driver of the card publishes it, section 5.2) or from the PKCS#11 module of the card (section 13.3). The PIN is entered by the signatory, or it is set from code only when the device and the policy of the provider allow it.
  3. The signature is created with PAdES, CAdES or XAdES, SHA-256 or stronger, with a time-stamp. For a long term validity use the B-LT or B-LTA level: the library creates it only with the complete validation data of the signer and of the time-stamping authority (section 12.3).
  4. The signature is validated with a validator that uses the EU trusted lists (section 14.6).
// A PAdES-B-LT signature with the certificate of a qualified token (the PIN window of the driver appears when the PIN is not set).
X509Certificate2 qualifiedCertificate = DigitalCertificate.LoadCertificate(true, DigitalCertificateSearchCriteria.Thumbprint, "FAC4D3EF766A59BB068DD90877267EBC56B4232A");

// The statements of the certificate (a declaration of the issuer, see below).
QualifiedCertificateInfo qc = DigitalCertificate.GetQualifiedCertificateInfo(qualifiedCertificate);
Console.WriteLine("Declared qualified: " + (qc != null && qc.IsQcCompliant) + ", key on a QSCD: " + (qc != null && qc.IsKeyOnQualifiedDevice));

PdfSignature pdfSignature = new PdfSignature(LibrarySerialNumber);
pdfSignature.LoadPdfDocument("contract.pdf");
pdfSignature.DigitalSignatureCertificate = qualifiedCertificate;
pdfSignature.SignatureStandard = PdfSignatureStandard.PadesLT;
pdfSignature.HashAlgorithm = SignLib.HashAlgorithm.SHA256;
pdfSignature.TimeStamping.ServerUrl = new Uri("https://tsa.example.com/qualified");   // the server of a qualified time-stamping provider

byte[] signedPdf = pdfSignature.ApplyDigitalSignature();
File.WriteAllBytes("contract[signed].pdf", signedPdf);

// The level that the signature has: LT.
PdfSignature verifier = new PdfSignature(LibrarySerialNumber);
verifier.LoadPdfDocument(signedPdf);
Console.WriteLine("Level: " + verifier.DocumentProperties.DigitalSignatures[0].Level);

14.4 What the certificate declares: QualifiedCertificateInfo

A qualified certificate declares its qualified status in the qcStatements extension (ETSI EN 319 412-5). DigitalCertificate.GetQualifiedCertificateInfo(certificate) reads these statements and returns a QualifiedCertificateInfo, or null when the certificate has no (readable) qcStatements extension:

PropertyStatement
IsQcCompliantQcCompliance (0.4.0.1862.1.1): the certificate declares that it is an EU qualified certificate.
IsKeyOnQualifiedDeviceQcSSCD (0.4.0.1862.1.4): the private key is in a qualified signature or seal creation device.
TypesQcType (0.4.0.1862.1.6): a list of QualifiedCertificateType: ESign (electronic signature), ESeal (electronic seal), Web (website authentication). Empty when not declared; an EU qualified certificate without QcType is for electronic signatures.
LegislationsQcCCLegislation (0.4.0.1862.1.7): the countries (ISO 3166 codes) under whose legislation a certificate qualified outside the EU is qualified. Empty when not declared.
RetentionPeriodYearsQcRetentionPeriod (0.4.0.1862.1.3): the years the information about the certificate is kept, or null.

DigitalCertificate.IsQualifiedCertificate(certificate) is the short form: true when the certificate declares QcCompliance. A qcStatements extension without it (for example only PSD2 or retention statements) is not a qualified certificate.

QualifiedCertificateInfo qc = DigitalCertificate.GetQualifiedCertificateInfo(signingCertificate);

if (qc == null || !qc.IsQcCompliant)
{
    Console.WriteLine("The certificate does not declare itself qualified.");
}
else
{
    bool forSignatures = qc.Types.Count == 0 || qc.Types.Contains(QualifiedCertificateType.ESign);
    bool forSeals = qc.Types.Contains(QualifiedCertificateType.ESeal);

    Console.WriteLine("Qualified (declared): signature " + forSignatures + ", seal " + forSeals
        + ", key on a QSCD " + qc.IsKeyOnQualifiedDevice
        + (qc.RetentionPeriodYears.HasValue ? ", retention " + qc.RetentionPeriodYears.Value + " years" : ""));
}
A declaration, not a proof

The statements are written by the issuer of the certificate: they are declarations. That a certificate is really qualified depends on its issuer being a qualified trust service on the trusted list of a member state, at the time of the signature; neither these properties nor CertificateValidator use the trusted lists. A qualified time-stamp has, by the same logic, TimestampInfo.IsQualifiedTimestamp as a declaration, and the trusted lists as the proof (section 14.6).

14.5 Test certificates

For the development of an application that handles qualified certificates, X509CertificateGenerator can create a test certificate with the qcStatements, the certificate policies and the subject identifiers of ETSI EN 319 412 (section 5.6); GetQualifiedCertificateInfo reads its statements as for a real qualified certificate. The signatures made with it have the correct structure, and they are not qualified: a validator reports that the certificate is not on a trusted list.

14.6 Validation with the EU DSS validator

The European Commission publishes the DSS (Digital Signature Service) library and a web validator that checks the signatures against the EU trusted lists and reports the level of the signature (AdES, AdES-QC, QESig, ...), the indications (TOTAL_PASSED, INDETERMINATE, TOTAL_FAILED) and the details of every check (certificate chain, revocation, time-stamps, format). To test a signature that the library created:

  1. Open the DSS demo validator: https://ec.europa.eu/digital-building-blocks/DSS/webapp-demo/validation.
  2. Upload the signed document: the PDF, the .p7m, the XML, the .asice. For a detached signature (.p7s, detached XAdES) upload also the original file.
  3. Read the simple report (the result of every signature) and the detailed report (every check, and why a check failed).

The results depend on the certificate: a signature with a qualified certificate on a QSCD, from a provider on the trusted list, is reported as a qualified signature (QESig); a signature with a certificate that is not on a trusted list, as the self-signed test certificates, has the indication INDETERMINATE (the signature is intact, the chain is not trusted); a document that was changed after it was signed has TOTAL_FAILED. The signatures of the long term levels (B-LT, B-LTA) show that the validation data and the time-stamps are present and valid.

The level that DSS reports for a baseline signature (PAdES-BASELINE-LT, CAdES-BASELINE-LTA...) is the level that the library reports in Level (section 12.4): in the validation runs of the library with DSS, the two levels are the same for every baseline signature. For the trust of the certificate without the trusted lists, use CertificateValidator (section 5.4).

Example: read the signatures of a signed PDF with SignLib and check the certificate of each signer with the .NET eIDAS Certificate Validator. The validator is a separate free library (EUTLValidator.zip, namespace EUTLValidator): CheckAt evaluates the certificate at the time of the signature, and an expired or revoked certificate keeps its qualified status.

// Read the signatures of a signed PDF with SignLib...
PdfSignature verifier = new PdfSignature(LibrarySerialNumber);
verifier.LoadPdfDocument(signedPdf);

// ...and check the certificate of each signer with the .NET eIDAS Certificate Validator,
// as it was when the document was signed (using EUTLValidator;).
EuTrustedListService service = new EuTrustedListService();

foreach (PdfSignatureInfo info in verifier.DocumentProperties.DigitalSignatures)
{
    CertificateQualificationResult q = service.CheckAt(info.SignatureCertificate, info.SignatureTime);

    Console.WriteLine(info.SignatureName + ": signature intact " + info.SignatureIsValid
        + ", certificate qualified " + q.IsQualified + " (" + q.Branches + ")");
}

15. Recipes

Complete solutions for the usual deployments: services without a user, batches, parallel signing, web services, and the handling of the network errors.

15.1 Signing without user intervention

A service, a scheduled task or a web application has no user who can select a certificate or type a PIN. Rules:

// A service: the certificate by its thumbprint from the Local Computer store, the PIN from a protected source.
X509Certificate2 certificate = DigitalCertificate.LoadCertificate(true, DigitalCertificateSearchCriteria.Thumbprint, "FAC4D3EF766A59BB068DD90877267EBC56B4232A", true);

if (certificate == null)
    throw new InvalidOperationException("The signing certificate was not found in the Local Computer store.");

DigitalCertificate.SmartCardPin = Environment.GetEnvironmentVariable("TOKEN_PIN");    // only when the certificate is on a token

PdfSignature pdfSignature = new PdfSignature(LibrarySerialNumber);
pdfSignature.LoadPdfDocument("source.pdf");
pdfSignature.DigitalSignatureCertificate = certificate;

byte[] signedPdf = pdfSignature.ApplyDigitalSignature();

15.2 Signing a folder

One signature object signs many documents: the certificate and the options are set once. A document that cannot be signed (a damaged file, a password-protected file without the password) must not stop the batch: catch the exception for each file and report it.

PdfSignature pdfSignature = new PdfSignature(LibrarySerialNumber);
pdfSignature.DigitalSignatureCertificate = signingCertificate;
pdfSignature.SigningReason = "I approve this document";

string[] files = Directory.GetFiles("source_folder", "*.pdf");
Directory.CreateDirectory("destination_folder");

int signed = 0;
for (int index = 0; index < files.Length; index++)
{
    try
    {
        pdfSignature.LoadPdfDocument(files[index]);
        File.WriteAllBytes(Path.Combine("destination_folder", Path.GetFileName(files[index])), pdfSignature.ApplyDigitalSignature());
        signed++;
    }
    catch (Exception ex)
    {
        Console.WriteLine(Path.GetFileName(files[index]) + " was NOT signed: " + ex.Message);
    }

    Console.WriteLine("Progress: " + (index + 1) + " of " + files.Length);
}

Console.WriteLine("Signed: " + signed + " of " + files.Length);

The same loop signs any file as .p7m with a CadesSignature object: File.WriteAllBytes(name + ".p7m", cadesSignature.ApplyDigitalSignature(file)).

15.3 Signing in parallel

The signing of a document with a software key uses the processor, and the time-stamp and the validation data wait for the network: many documents are signed faster in parallel. The rules of section 4.9 apply:

X509Certificate2 certificate = DigitalCertificate.LoadCertificate("cert.pfx", "123456");    // shared by the threads
string[] files = Directory.GetFiles("source_folder", "*.pdf");
Directory.CreateDirectory("destination_folder");

ConcurrentQueue<string> errors = new ConcurrentQueue<string>();
int signed = 0;
int processed = 0;

ParallelOptions options = new ParallelOptions { MaxDegreeOfParallelism = Math.Min(4, Environment.ProcessorCount) };

Parallel.ForEach(
    files,
    options,

    // localInit: one PdfSignature object for every worker task.
    () =>
    {
        PdfSignature threadSignature = new PdfSignature(LibrarySerialNumber);
        threadSignature.DigitalSignatureCertificate = certificate;
        return threadSignature;
    },

    (file, loopState, index, threadSignature) =>
    {
        try
        {
            // With an external provider or a PIN, set them here, on the thread that signs, before every file:
            // DigitalCertificate.UseExternalSignatureProvider = provider;
            threadSignature.LoadPdfDocument(file);
            File.WriteAllBytes(Path.Combine("destination_folder", Path.GetFileName(file)), threadSignature.ApplyDigitalSignature());
            Interlocked.Increment(ref signed);
        }
        catch (Exception ex)
        {
            errors.Enqueue(Path.GetFileName(file) + ": " + ex.Message);
        }

        Console.WriteLine("Processed " + Interlocked.Increment(ref processed) + " of " + files.Length);
        return threadSignature;
    },

    threadSignature => { });

foreach (string error in errors)
    Console.WriteLine("NOT signed: " + error);

Stopping the loop: pass a CancellationToken in ParallelOptions (for example one that the user cancels with Ctrl+C); the files in progress are finished and the others are skipped. The sample Batch Signing with Parallelism shows the cancellation, the comparison with the sequential loop and the damaged file.

The demo version

The signing of PDF documents is not slowed in the demo version, but the CAdES, XML, XAdES, Office and ASiC-E operations wait 10 seconds before each signature or verification (section 2.4). A parallel batch of these formats is still faster than a sequential one, but the times do not show the speed of the licensed library.

15.4 Network errors: retry and time limits

The time-stamp and the validation data depend on servers that you do not control. A time-stamping server that does not answer throws WebException. When the CRL or the OCSP response of a certificate cannot be downloaded for a long term signature, the signature is not created: ValidationDataException lists the certificates and the reasons (unless AllowIncompleteValidationData is true). RevocationCache remembers a failed download for RevocationCache.FailureRetention (60 seconds by default), so that the next documents do not wait again for the same server: a retry of a ValidationDataException must wait longer than that. A batch should retry the transient failures with a pause, and not retry the errors of the document or of the key:

public static class Retry
{
    // Runs the signing and retries it when a server fails (a transient error), with a pause.
    public static byte[] SignWithRetry(Func<byte[]> sign, int attempts = 3)
    {
        for (int attempt = 1; ; attempt++)
        {
            try
            {
                return sign();
            }
            catch (WebException) when (attempt < attempts)
            {
                // The time-stamping server: a growing pause.
                Thread.Sleep(TimeSpan.FromSeconds(2 * attempt));
            }
            catch (ValidationDataException) when (attempt < attempts)
            {
                // An OCSP responder or a CRL server: the failure is remembered for FailureRetention.
                Thread.Sleep(RevocationCache.FailureRetention + TimeSpan.FromSeconds(5));
            }
        }
    }
}
PdfSignature pdfSignature = new PdfSignature(LibrarySerialNumber);
pdfSignature.LoadPdfDocument("source.pdf");
pdfSignature.DigitalSignatureCertificate = signingCertificate;
pdfSignature.SignatureStandard = PdfSignatureStandard.PadesLT;
pdfSignature.TimeStamping.ServerUrl = new Uri("https://ca.signfiles.com/TSAServer.aspx");
pdfSignature.TimeStamping.ServerTimeout = 15000;     // milliseconds, the time-stamp request

// Process-wide, once when the application starts: the OCSP and CRL requests, and the proxy.
NetworkSettings.RevocationTimeout = 15000;           // milliseconds
// NetworkSettings.Proxy = new WebProxy("http://proxy.company.com:8080");

byte[] signedPdf = Retry.SignWithRetry(() => pdfSignature.ApplyDigitalSignature());

The signing time of a document that is signed again in a retry is the time of the last attempt. The other CryptographicException errors (a key that cannot be used, a damaged document), CertificateRevokedException (a certificate of the chain is revoked) and ArgumentException are not transient: do not retry them. When the servers are reached through a proxy, set NetworkSettings.Proxy (section 4.10).

15.5 A signing web service

A web application receives documents, signs them and returns them, without temporary files: byte[] in, byte[] out. The rules: a signature object per request, the certificate loaded once and shared, the serial number and the certificate password from the configuration, and the authentication and the authorization of the callers: a signing endpoint that anyone can call signs for anyone. The sample PDF Signing Web Service ASP.NET Core is a minimal API with these endpoints:

EndpointWhat it does
POST /api/sign-pdfSigns the PDF in the body with the certificate of the server and returns the signed PDF.
POST /api/verify-pdfReturns the signatures of the PDF as JSON.
POST /api/prepare, POST /api/finalizeThe two-phase signature for a client that owns the private key: the server prepares the signature and keeps it; the client signs the data locally; the server completes the document.
// Excerpt of the sample "PDF Signing Web Service ASP.NET Core" (the whole project is in the sample set for .NET).
X509Certificate2 serverCertificate = DigitalCertificate.LoadCertificate(Path.Combine(AppContext.BaseDirectory, "cert.pfx"), CertificatePassword);   // loaded once

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
WebApplication app = builder.Build();

app.MapPost("/api/sign-pdf", async (HttpRequest request) =>
{
    try
    {
        PdfSignature pdfSignature = new PdfSignature(LibrarySerialNumber);                  // an object per request
        pdfSignature.LoadPdfDocument(await ReadBodyAsync(request));
        pdfSignature.DigitalSignatureCertificate = serverCertificate;
        pdfSignature.SignatureStandard = PdfSignatureStandard.Pades;

        return Results.File(pdfSignature.ApplyDigitalSignature(), "application/pdf", "signed.pdf");
    }
    catch (Exception ex)
    {
        return Results.BadRequest("The document cannot be signed: " + ex.Message);
    }
});

app.Run();

The matching client (the sample PDF Signing Web Service Client, .NET and .NET Framework 4.6.2) signs the data of the two-phase signature with its own key:

  1. POST /api/prepare with the PDF and the public certificate; the response has a session identifier and the data to sign;
  2. the client signs the data with its private key (a PFX file, a token) and sends the signature value;
  3. POST /api/finalize with the identifier and the signature value; the response is the signed PDF.

In the sample the prepared signature is kept in the memory of the server (a session of ten minutes, used one time). A production service stores it in a database or a distributed cache (PendingExternalSignature is serializable as JSON), authenticates the callers, uses HTTPS and limits the size of the requests. Kestrel does not allow synchronous reads of the body: read it with CopyToAsync.

What the library keeps in the process of the service:

15.6 Linux and containers

15.7 Signing large documents

In a web service or a batch, the memory is shared by many documents. For large documents, sign from streams: the document stays in its stream (a file, the storage of the application) and is not copied into memory; only the signature, and for the long term levels the validation data and the time-stamp, are held in memory.

FormatHow
PDFPdfSignature.LoadPdfDocument(Stream), then ApplyDigitalSignature(Stream output): the document is copied from its stream to the output, followed by the new revision (section 6.12). The input stream must stay open and unchanged until the document is signed. A PDF document is limited to 2 GB (IOException).
CAdESCadesSignature.ApplyDigitalSignature(Stream input, Stream output) reads the content once to compute its digests (section 7.6). A detached signature (IsDetachedSignature = true, a .p7s file) reads any stream once and writes only the signature; an attached signature (.p7m) reads a seekable input a second time and writes the content again into the output. CAdES has no 2 GB limit.
// PDF: the document stays in the input file; the signed document is written to the output file.
using (FileStream input = File.OpenRead("large.pdf"))
using (FileStream output = File.Create("large[signed].pdf"))
{
    PdfSignature pdfSignature = new PdfSignature(LibrarySerialNumber);
    pdfSignature.DigitalSignatureCertificate = signingCertificate;
    pdfSignature.LoadPdfDocument(input);
    pdfSignature.ApplyDigitalSignature(output);
}

// CAdES: a detached signature (.p7s) of a file of any size, read once.
using (FileStream input = File.OpenRead("archive.zip"))
using (FileStream output = File.Create("archive.zip.p7s"))
{
    CadesSignature cadesSignature = new CadesSignature(LibrarySerialNumber);
    cadesSignature.DigitalSignatureCertificate = signingCertificate;
    cadesSignature.IsDetachedSignature = true;
    cadesSignature.ApplyDigitalSignature(input, output);
}

15.8 Check the certificate before signing

Many failures in production are a certificate that expired yesterday. A cheap check at the start of the application and before every batch avoids signing with a certificate that every validator will reject:

public static class CertificateGuard
{
    // Throws when the certificate cannot be used to sign today.
    public static void EnsureCanSign(X509Certificate2 certificate, TimeSpan warnBefore)
    {
        if (!certificate.HasPrivateKey)
            throw new InvalidOperationException("The certificate has no private key.");

        if (DigitalCertificate.VerifyDigitalCertificate(certificate, VerificationType.LocalTime) != CertificateStatus.Valid)
            throw new InvalidOperationException("The certificate is expired or not yet valid: " + certificate.NotBefore + " - " + certificate.NotAfter);

        if (certificate.NotAfter - DateTime.Now < warnBefore)
            Console.WriteLine("WARNING: the certificate expires on " + certificate.NotAfter.ToShortDateString());

        // Optional: the revocation status (an OCSP or CRL request).
        if (DigitalCertificate.VerifyDigitalCertificate(certificate, VerificationType.OCSP) == CertificateStatus.Revoked)
            throw new InvalidOperationException("The certificate was revoked.");
    }
}

16. Sample projects

The download of the library has two sets of sample projects with the same structure: .NET (SDK-style projects for .NET 8 and later, in the folder NET Sample Projects) and .NET Framework 4.6.2 (for .NET Framework 4.6.2 and later, in the folder NET Framework Sample Projects). Every console project is a small program with a comment at the beginning of Program.cs that says what it shows, with the link of this manual. Every project has the input files that it needs (cert.pfx, source.pdf, test.txt...) in its output folder, and a solution file; the library is referenced from the folder SignLib of the set.

16.1 Getting started

SampleWhat it shows.NET.NET Framework
Start HereThe smallest complete program: load a PFX certificate, sign a PDF file and read the validity, level and signer of the signature. Copy it to start your own project. → section 3.1yesyes

16.2 PDF

SampleWhat it shows.NET.NET Framework
PDF Digital SignatureThe first sample: a certification signature, a second PAdES signature with an image, a signature on several pages, the list of the signatures. → section 6.4yesyes
PDF Digital Signature with PFX CertificateThe simplest way to sign: a certificate from a PFX file or from the bytes of a PFX file, the signed document as a byte array, the verification. → section 5.2yes—
PDF Digital Signature Multiple Pages and SignersThe pages of the signature, three signers, fonts, right to left text, an invisible signature. → section 6.4yesyes
PDF Digital Signature - Adobe Signature FieldSigning an existing signature field of a form. → section 6.7yesyes
PDF Digital Signature Long-Term Validation PAdES-LTVPAdES-LT: the validation data in the document. → section 6.9yesyes
PDF Digital Signature Long-Term Archival PAdES-LTAPAdES-LTA and the renewal of the document time-stamp. → section 12.6yesyes
PDF Timestamp SignatureA document time-stamp. → section 6.8yesyes
PDF Digital Signature with EncryptionPassword and certificate encryption, signing and encrypting, opening encrypted documents. → section 6.10yesyes
PDF Signature VerificationA standalone verifier: integrity, covered bytes, certificate, chain, revocation, the kind of signature. → section 6.11yesyes

16.3 CAdES / PKCS#7

SampleWhat it shows.NET.NET Framework
P7M P7S CAdES Digital SignatureSigning any file as .p7m or .p7s, the verification, the extraction of the signed file. → section 7.1yesyes
P7M P7S CAdES Long-Term and Co-SignatureThe CAdES levels, a time-stamped signature, co-signatures, the level detected from the file. → section 7.2yesyes
CAdES Digital Signature Long-Term Archival CAdES-LTACAdES-LTA, attached (.p7m) and detached (.p7s), and its verification. → section 7.2yesyes

16.4 XML

SampleWhat it shows.NET.NET Framework
XML Digital Signature - XMLDSigEnveloped XMLDSig, hash and canonicalization options, a second signature, verification. → section 8.1yes—
XML Digital Signature SHA256 - XMLDSigThe XMLDSig sample of the .NET Framework set. → section 8.1—yes
XML Digital Signature SHA256 - XMLDSig StreamsSigning and verifying XML documents read from and written to streams, with exclusive canonicalization. → section 8.1—yes
XML Digital Signature - XAdESXAdES B-B, B-T, detached, signature policy, LTA and the renewal of the archive time-stamp. → section 8.2yes—
XML Digital Signature SHA256 - XAdESThe XAdES sample of the .NET Framework set. → section 8.2—yes
XML Digital Signature Long-Term Archival XAdES-LTAXAdES-LTA, enveloped and detached: the level read from the signature, the renewal of the archive time-stamp, a document changed after the signature. → section 8.2yesyes

16.5 Office and ASiC-E

SampleWhat it shows.NET.NET Framework
Office Digital Signature (DOCX, XLSX, PPTX)All the features of OfficeSignature: levels, signature lines, several signers, in memory, verification. → section 9yesyes
ASiC-E Container Digital SignatureAll the features of AsicSignature: creation, options, co-signatures, renewal, reading, tamper detection. → section 10yesyes
ASiC-E Digital Signature Long-Term Archival XAdES-LTAA container with an XAdES-LTA signature: the level read from the container, the renewal of the archive time-stamp, a container changed after the signature. → section 10.5yesyes

16.6 Time-stamps

SampleWhat it shows.NET.NET Framework
TSR Timestamp a FileTime-stamping a file (.tsr, .tsd) and verifying it. → section 11.2yesyes
Timestamp Renewal PDF ASiC XAdESThe renewal of the archive time-stamps of PDF, ASiC-E and XAdES, with a renewal rule. → section 12.6yesyes

16.7 Long-term validation and servers

SampleWhat it shows.NET.NET Framework
Signature Level and Validation DataSigns PDF, CAdES and XAdES files at level LT and reads the real level and validation data of each signature, including the ValidationDataException for a certificate without revocation information. → section 12.4yesyes
Extend and Renew Long-Term SignaturesRaises XAdES and ASiC-E signatures from B to LTA and runs an archive routine that renews the PDF, CAdES, XAdES and ASiC-E archive time-stamps only when the renewal date is near. → section 12.6yesyes
Offline Server, Caches and Network SettingsSigns and verifies documents on a server without Internet access: the revocation cache, a revocation data provider, the certificate cache, the network and security settings. → section 12.5yesyes

16.8 Certificates

SampleWhat it shows.NET.NET Framework
Create PFX Digital CertificatesRoot, issued, self-signed and ECDSA certificates. → section 5.6yesyes
Certificate ValidationValidity period, CRL, OCSP, the revocation date, key usages, the qualified status. → section 5.4yesyes
Custom Certificate SelectionA custom selection of the certificate from the Windows store. → section 5.2—yes
Certificate SelectorA selection window for the certificates (a component used by the Windows Forms samples). → section 5.2—yes

16.9 External keys

SampleWhat it shows.NET.NET Framework
PDF Digital Signature with PKCS11 Smart CardA token or a smart card through its PKCS#11 module; the certificate by thumbprint. → section 13.3yesyes
P7M P7S CAdES Digital Signature with PKCS11 Smart CardThe same for a .p7m file. → section 13.3yesyes
PDF Digital Signature with PKCS11 Driver for HSMAn HSM through its PKCS#11 module. → section 13.3yesyes
PDF Digital Signature - External SignatureA custom signature engine as IExternalSignature. → section 13.1yes—
PDF Remote External Digital SignatureA remote signing service (the demo service of the vendor). → section 13.6yesyes
P7M P7S CAdES Remote External Digital SignatureThe same for a .p7m file. → section 13.6yesyes
PDF Remote External Digital Signature (Sample)The two-phase signature (Prepare / Finalize) with a simulated signer. → section 13.5yes—
PDF Digital Signature with Azure Key Vault CertificateAn exportable certificate stored in Azure Key Vault. → section 13.6yes—
PDF Digital Signature with Azure Key Vault Nonexportable HSM CertificateA key that never leaves Azure Key Vault or Managed HSM. → section 13.6yes—

16.10 Batches and services

SampleWhat it shows.NET.NET Framework
Batch PDF Signature Without User InterventionA folder signed with a certificate from the Windows store, without windows. → section 15.1yesyes
Batch P7M P7S CAdES and PDF SignaturesA folder signed as PDF and as .p7m; progress; a parallel loop. → section 15.2yesyes
Batch Signing with ParallelismSequential and parallel signing, progress, cancellation, errors. → section 15.3yesyes
PDF Signing Web Service ASP.NET CoreA signing web service (minimal API), in memory, with two-phase signing. With a Dockerfile and README-Docker.txt to run it in a Linux container. → section 15.5yes—
PDF Signing Web Service ClientThe client of the service: server-side signing, verification, two-phase signing with the key of the client. → section 15.5yesyes

16.11 Applications with a user interface and VB.NET

SampleWhat it shows.NET.NET Framework
P7M P7S CAdES Signer Windows FormsA Windows Forms application that signs files as .p7m / .p7s.yesyes
PDF Signer Windows FormsA Windows Forms application that signs PDF documents.—yes
DOCX Signer Windows FormsA Windows Forms application that signs Office documents.—yes
VB.NET Digitally Sign a PDF FileThe PDF signature in VB.NET.—yes
VB.NET CAdES and PKCS#7 Digital SignatureThe CAdES signature in VB.NET.—yes
VB.NET Office Digital Signature (DOCX, XLSX, PPTX)The Office signature in VB.NET.—yes

The projects that exist in one set only were written for the platform of that set: the Azure samples, the web service, the external signature, the PFX sample and the two-phase sample are in the .NET set; the PDF and DOCX Windows Forms applications, the certificate selection samples and the VB.NET projects are in the .NET Framework set. The samples that exist in both sets do the same thing.

17. Problems and solutions

The messages are the ones that the library writes in the exception; part of a message is enough to find the line. When the cause is not in the table, read the inner exception (ex.InnerException) and the full text of ex.ToString().

17.1 Project and installation

SymptomCauseSolution
FileNotFoundException or TypeLoadException for System.Security.Cryptography.Pkcs, System.IO.Packaging, System.Drawing.Common...A .NET project that references SignLib.dll as a file does not get the packages that the library uses.Add the NuGet packages of section 2.2, version 10.0.15 or newer.
The signed PDF has the text SignLib.dll DEMO VERSION on the first page; the console shows a red message; every operation waits 10 secondsThe library runs as the demo version: the serial number is missing or it is not valid.Pass the serial number of your license to the constructors (section 2.4). Check that no space or line break is in the string (the library trims the spaces at the ends).
The PKCS#11 module cannot be loaded (a bad image format error)A 64-bit process loads a 32-bit module or the reverse, or the path of the module is wrong.Use the module that matches the process (section 13.3).
The assembly is not found at run time, or a method is missingThe .NET Framework build of SignLib.dll is used in a .NET project, or the reverse; or an older SignLib.dll stays in the output folder.Reference the build of the folder that matches the target framework of the project (section 1.2) and delete the old copies of the DLL.

17.2 Signing

SymptomCauseSolution
NullReferenceException: Digital certificate is not set.DigitalSignatureCertificate was not set (or LoadCertificate returned null because the user cancelled, or no certificate matched).Check the result of LoadCertificate before you use it.
NullReferenceException: Document is not loaded.LoadPdfDocument was not called before ApplyDigitalSignature (or before AddSignatureField).Load the document first.
CryptographicException: The private key for this certificate was not found. / RSA private key not found on certificate.The certificate has no private key: it was loaded from a .cer file or the key is not accessible to the process.Load the PFX file, or the certificate from the store of the account that runs the process. For a key outside the process use an external provider (section 13).
CryptographicException when a PFX is loaded (The specified network password is not correct, Failed to load certificate with provided data/password.)A wrong password or a damaged PFX file; or a PFX with a key algorithm that the platform cannot import.Check the password and the file; open it with certmgr to see if it is valid.
The PIN window of the token appears on every signature, or in a service the call waits for the PINThe PIN was not given to the library, or the driver does not accept it from the application.Set DigitalCertificate.SmartCardPin before every signature on the thread that signs; for the tokens that do not take it use PKCS#11 (section 5.2).
CryptographicException: Bypassing PIN Exception ...The PIN cannot be set for the key (an unsupported provider, or a key that is not a smart card key).Remove SmartCardPin and let the driver ask, or use PKCS#11.
CryptographicException: The signature ... does not fit in the space reserved for it (PDF)The signature, with the validation data or the certificates, is larger than the space reserved in the document.Use a smaller revocation level (PadesLtvLevel.IncludeOcspOnly), or a certificate with a smaller chain; avoid the CRLs that are very large.
ArgumentOutOfRangeException: Invalid signature page number.SignaturePage or an item of SignaturePages is not a page of the document.Use a page from 1 to the number of pages, or int.MaxValue for the last page.
CryptographicException: A document that is already signed or certified cannot be encrypted.PdfSignature.Encryption is set for a document that already has signatures.Encrypt before the first signature, or sign and encrypt in one operation (section 6.10).
InvalidOperationException: Only a single document certification is allowed ...A second certification signature (CertifySignature other than NotCertified).A document has one certification signature, the first one. The other signers use NotCertified.
A password-protected PDF cannot be loadedThe password was set after LoadPdfDocument, or it is wrong.Set DocumentProperties.Password before the load.
The visible signature shows ? instead of the characters of a languageThe standard font (FontName) has no glyphs for that script.Set FontFile to a TrueType font that has them (section 6.5).
NotSupportedException for SHA-1XML, XAdES, Office and ASiC-E signatures are not created with SHA-1.Use SHA256 (the default) or stronger.
ArgumentException: TimeStamping.ServerUrl must be set for XAdES-T, XAdES-LT and XAdES-LTA signatures.A level with a time-stamp without a time-stamping server (the same for Office and ASiC-E).Set TimeStamping.ServerUrl, or use XadesB.
NotSupportedException: XAdES-LTA is not supported for Office documents ...Office documents have the levels B, T and LT.Use XadesLT, or an ASiC-E container for the LTA level.
NotSupportedException: Visible signatures (signature lines) are supported only for Word documents (docx). / PlatformNotSupportedException: ... require WindowsA signature line on a workbook, on a presentation, or on a system that is not Windows.Sign them without SignatureLine (an invisible signature).
InvalidOperationException: The document is already signed: adding a signature line would invalidate its signatures.The signature lines were added after the first signature.Add the lines of all the signers before the first signature (section 9.2).
CryptographicException: A new signature cannot be added because it would invalidate an existing XML signature.The document has a signature made by another program with the enveloped-signature transform.Sign a copy of the document in another file, or keep one signature per document.
ArgumentException: For a detached signature the output (signature) file must be different from the signed file.The output path of a detached XAdES signature is the path of the signed file.Use another path for the signature file.
CryptographicException: The external signature provider returned an empty signature. / The signature returned by the external signature provider is not valid for the ...The provider signed with another key, with another hash algorithm, or returned a wrong encoding.Hash message with the algorithm of the OID that you receive; use the key of the certificate that you set; return PKCS#1 v1.5 (RSA) or r || s / DER (ECDSA) (section 13).
CryptographicException: The private key is held by the external signature provider.An operation that needs the private key (for example the use of SignData) with a certificate that has none.Use the signature classes with UseExternalSignatureProvider.
IOException: The PDF document is larger than 2 GB: the PDF documents of 2 GB or more are not supported.A PDF document of 2 GB or more is loaded (LoadPdfDocument), or a signed document would reach 2 GB. A file loaded by its path gets the IOException of .NET for files of 2 GB or more.The PDF documents are limited to 2 GB (section A.2). Sign a very large file as a detached CAdES signature (.p7s), which has no such limit (section 7.6).
ValidationDataException: The revocation data (OCSP response or CRL) required for a long term signature could not be obtained ...A long term level (PAdES-LT/LTA, CAdES-LT/LTA/C/XL/A, XAdES-LT/LTA, also for Office and ASiC-E) was requested and the OCSP response or the CRL of a certificate of the signer or of the time-stamping authority could not be obtained: no address in the certificate, a server that did not answer, a CRL larger than MaxCrlSize. No signed document is produced. The message and MissingData list the certificates and the reasons.Check the connection to the OCSP and CRL servers and the proxy (section 4.10); use a certificate issued by a CA that publishes them. To create the signature with the data that could be obtained, set AllowIncompleteValidationData = true (section 12.4).
InvalidOperationException: PAdES-LT and PAdES-LTA signatures are time-stamped: set TimeStamping.ServerUrl ... / ... PadesLtvLevel cannot be None ...A PAdES-LT or PAdES-LTA signature without a time-stamping server, or with PadesLtvLevel.None.Set TimeStamping.ServerUrl and a PadesLtvLevel other than None.
CertificateRevokedException: The certificate '...' is revoked since ...The OCSP response or the CRL obtained for a long term signature says that a certificate of the signer, or of the time-stamping authority, is revoked (a suspended certificate too). No signed document is produced; AllowIncompleteValidationData does not change it.Sign with a valid certificate, or use another time-stamping server. Certificate, RevocationTime, RevocationReason and IsTimestampAuthority of the exception say which certificate it is.
SecurityLimitException: The container has ... entries, more than SecurityLimits.MaxZipEntries ... (or MaxZipEntrySize, MaxZipTotalSize, MaxCompressionRatio, an entry present more than once)An ASiC-E container or an Office package exceeds a limit of SecurityLimits, or has a structure that is refused for security reasons.Check the origin of the file. For trusted files larger than the defaults, raise the limit of SecurityLimits (section 4.11, section A.2).
XmlException: For security reasons DTD is prohibited in this XML document ...The XML document has a document type declaration (<!DOCTYPE>); the documents with a DTD are refused by default.Remove the DTD, or, for trusted documents, set SecurityLimits.AllowXmlDtd = true (external entities are never loaded) (section 4.11).

17.3 Verification

SymptomCauseSolution
SignatureIsValid is false for a document that was just signedThe document was changed after the signature: a re-save, a conversion, a repair of the PDF, an added byte, another encoding of an XML file, a download that changed the line ends.Keep the signed bytes as they are. Compare the checksum before and after the transfer; transfer in binary mode.
SignatureIsValid is true but Adobe Reader shows the signature as validity unknownThe certificate of the signer (or its root) is not trusted by the reader. It is the trust, not the integrity.Use a certificate issued by a trusted certification authority, or add the certificate to the trusted identities of the reader (section 6.15). Step by step: “Signature validity is unknown” in Adobe: causes and solutions.
The document is intact but the last signature does not cover the whole fileData was appended after the signature (a revision that is not signed).Check the /ByteRange as in section 6.11.
SignatureIsValid is false and SignatureAlgorithmNotSupported is trueThe signature algorithm or the digest algorithm of the signature (PDF, CAdES) is not supported by the library: the signature could not be verified, but it was not found altered.Verify the signature with another validator. Do not treat it as a changed document.
CryptographicException: Invalid or corrupt CAdES/PKCS#7 signed data.The file is not a CMS signature (a .p7m that was damaged, or a file with another format).Check the origin of the file; open it with another tool.
A detached .p7s verifies as invalid or its document is nullThe original document was not given.Use new CadesVerify(signature, originalDocument, serial) (section 7.7).
CryptographicException: Verification failed: No digital signature was found in the document.The XML (or Office) document has no signature.Check GetNumberOfSignatures first.
CryptographicException: The signature is detached: the signed data is not included in the XML document.A detached XAdES signature verified without the signed file.Use VerifyDigitalSignature(signatureFile, originalFile).
An ASiC-E container is false after a file was added or changedEvery signature covers all the files of the container: it is the expected result.Create a new container, or add a signature with AddSignature (it covers the new content).
NotSupportedException: The container has CAdES signatures (*.p7s); only XAdES signatures are supported.An ASiC-E container with CAdES signatures.Verify it with another tool.

17.4 Time-stamps, revocation data, network

SymptomCauseSolution
WebException: Invalid time stamping response. (with a status or a reason)The time-stamping server is unreachable, it refused the request (authentication, policy, hash algorithm), or it is not an RFC 3161 server.Open the address in a browser; check UserName, Password, PolicyOid and HashAlgorithm (try SHA-256); check the proxy and the firewall; use Retry (section 15.4).
WebException with the status code 407 (Proxy Authentication Required)The network uses a proxy that requires authentication, and the library has no credentials for it (or the credentials are wrong).Set NetworkSettings.Proxy with the address and the credentials of the proxy, or with the system proxy and the Windows credentials (section 4.10).
WebException: The response is larger than NetworkSettings.MaxResponseSize ...A time-stamp, an OCSP response, a CRL or a downloaded document is larger than NetworkSettings.MaxResponseSize (50 MB by default).Check the address; for a very large CRL that you trust, raise NetworkSettings.MaxResponseSize (section 4.10).
The request waits and fails after 20 secondsThe default time-out of the server (ServerTimeout) or of the downloads (NetworkSettings.RevocationTimeout, the same setting as DigitalCertificate.Timeout).Increase the value, or fix the network access.
A request fails on .NET Framework with an error about the secure channelThe server requires TLS 1.2 and the application does not enable it.Set ServicePointManager.SecurityProtocol at the start of the program (section 2.3).
The PAdES-LT or XAdES-LT signature has no revocation dataAllowIncompleteValidationData is true, and the certificate has no CRL or OCSP address, the servers did not answer, or the CRLs are larger than MaxCrlSize (with the default false, a ValidationDataException is thrown instead).Use a certificate that publishes them; check the connection; set MaxCrlSize higher or IncludeOcspOnly (section 12.3).
CertificateStatus.NotPresentThe certificate has no CRL address, or no OCSP responder, for the verification type that you asked.It is normal for self-signed certificates; try the other type.
CertificateStatus.UnknownThe CRL or the OCSP server could not be reached or its response could not be read.Retry; do not treat it as Valid.
ArgumentException from AddArchiveTimestampThe time-stamping server is not set, or the output is the original file.Set TimeStamping.ServerUrl; use another output path.

17.5 Certificates

SymptomCauseSolution
LoadCertificate by criterion returns nullNo certificate in that store matches (the store of the current user versus the local computer; a thumbprint with spaces or invisible characters; validOnly filters the expired certificates).Check the store and the value; paste the thumbprint without spaces; try validOnly = false.
A certificate imported in Windows works for a user and not for a serviceThe service account has another certificate store and no permission for the key.Install the certificate in the Local Computer store and give the account the permission to use the key; load with fromLocalMachine = true (section 15.1).
CryptographicException: KeyEncipherment and DataEncipherment cannot be used with an ECDSA key (RFC 5480).A generated ECDSA certificate with an RSA-only key usage.Use DigitalSignature and NonRepudiation for ECDSA keys.
The certificates created with the demo version expire in 30 daysThe demo version limits the validity.Register the library (section 2.4).
CryptographicException: The certificate serial number does not appear on the CRL.GetCertificateRevocationDate was called for a certificate that is not revoked.Call it only when VerifyDigitalCertificate returned Revoked.
CryptographicException: The CSR could not be parsed. / Root certificate is not loaded.The CSR is not a PKCS#10 request in PEM, or LoadRootCertificate was not called before GenerateCertificateFromCSR.Check the text of the request and load the CA first.

17.6 If the problem remains

18. API reference

This reference lists the public types of the library by namespace. It is generated from the assembly and from its XML documentation (SignLib.xml), so it has the exact signatures. The members that are marked as hidden from IntelliSense in the library are not listed. In the guide chapters, a name written in this font is a link to its entry here; use the search box of the contents to find a member.

Conventions: the indexes of the signatures are 0-based; a default value is the value that a property has until you set it; time values are UTC unless the description says local time; the methods that have a Stream, byte[] and path overloads do the same with every kind of input.

18.1 Namespace SignLib

TypeDescription
LongTermArchive static classThe renewal dates of the long term archival signatures (PAdES-LTA, CAdES-LTA, XAdES-LTA and ASiC-E with XAdES-LTA).
NetworkSettings static classThe network settings of the requests sent by the library: OCSP requests, CRL downloads, time-stamp requests and documents loaded from a URL.
OfficeSignature classSigns Office Open XML documents (docx, xlsx, pptx and their macro-enabled versions) with package digital signatures compatible with Microsoft Office: XAdES signatures (the levels B, T and LT), invisible or visible (an Office signature line of a Word document), and verifies them.
SecurityLimitException classThe exception thrown when a document or container exceeds a limit of SecurityLimits (e.g.
SecurityLimits static classThe limits applied to the documents and containers that the library reads (they may come from untrusted sources): XML documents (XAdES, XMLDSig, ASiC, Office), ZIP containers (ASiC-E) and Office packages.
HashAlgorithm enumHash algorithms used to create digital signatures and time-stamp requests.
SignatureLevel enumThe effective level of an AdES signature (ETSI baseline levels), determined from what the signature contains.

LongTermArchive static class

Namespace: SignLib · Assembly: SignLib.dll

public static class LongTermArchive

The renewal dates of the long term archival signatures (PAdES-LTA, CAdES-LTA, XAdES-LTA and ASiC-E with XAdES-LTA). An archived document stays verifiable while the certificate chain of the time-stamping authority of its last archive (or document) time-stamp is valid: it must be renewed (a new archive time-stamp, see PdfSignature.AddArchiveTimestamp, CadesSignature.AddArchiveTimestamp, XadesSignature.AddArchiveTimestamp and AsicSignature.AddArchiveTimestamp) before that date, and also when its algorithms become weak. Plan the renewal with a margin (e.g. 90 days before the returned date).

Methods
public static DateTime? GetAsicRenewalDate(byte[] container)

Gets the renewal date of an ASiC-E container: the first expiry date (UTC) of the certificate chain of the time-stamping authority of the last archive time-stamp of its XAdES signatures.

container
The ASiC-E container.

Returns. The date, or null when no signature has an archive time-stamp.

public static DateTime? GetCadesRenewalDate(byte[] signature)

Gets the renewal date of a CAdES signature: the first expiry date (UTC) of the certificate chain of the time-stamping authority of the last archive time-stamp (archive-time-stamp-v3) of its signers.

signature
The CAdES signature.

Returns. The date, or null when the signature has no archive time-stamp.

public static DateTime? GetPdfRenewalDate(IEnumerable<PdfSignatureInfo> signatures)

Gets the renewal date of a PDF document: the first expiry date (UTC) of the certificate chain of the time-stamping authority of its last document time-stamp.

signatures
The signatures of the document (PdfSignature.DocumentProperties.DigitalSignatures).

Returns. The date, or null when the document has no document time-stamp.

public static DateTime? GetXadesRenewalDate(string signatureFile)

Gets the renewal date of a XAdES signature file: the first expiry date (UTC) of the certificate chain of the time-stamping authority of the last archive time-stamp of its signatures.

signatureFile
The path of the XML document (enveloped signature) or of the detached signature.

Returns. The date, or null when no signature has an archive time-stamp.

NetworkSettings static class

Namespace: SignLib · Assembly: SignLib.dll

public static class NetworkSettings

The network settings of the requests sent by the library: OCSP requests, CRL downloads, time-stamp requests and documents loaded from a URL.

Properties
public static bool AllowLegacyTls { get; set; }

Gets or sets a value indicating whether the deprecated TLS 1.0 and TLS 1.1 versions are allowed for the requests of the library (for legacy servers; a server that supports TLS 1.2 or 1.3 still negotiates it). The default value is true. On .NET, the setting applies only to the requests of the library. On .NET Framework, the TLS versions belong to the whole application (ServicePointManager): the library adds TLS 1.2, and TLS 1.0 and 1.1 only when this setting is true, before its first request; it never removes the versions of the application.

public static bool BlockPrivateAddresses { get; set; }

Gets or sets a value indicating whether the URLs read from the certificates (OCSP responders, CRL distribution points) are refused when they point to a local or private address (localhost, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, link-local, fc00::/7...), against the server-side request forgery (SSRF) through the certificates of untrusted documents. The default value is false (the certification authorities of an internal PKI often use private addresses). The URLs set by the application (time-stamp server, PDF URL) are not affected.

public static int MaxConnectionsPerServer { get; set; }

Gets or sets the maximum number of simultaneous connections of the library to the same server (time-stamping, OCSP, CRL), for the documents signed in parallel. The default value is 16 (on .NET Framework, the default of the applications is only 2). It applies to .NET Framework; on .NET the connections are not limited.

public static int MaxRedirects { get; set; }

Gets or sets the maximum number of HTTP redirects followed by a request. The default value is 3; 0 means that the redirects are not followed. A HTTPS request is never redirected to HTTP, and the credentials (time-stamp server user and password, client certificate) are never sent to another server.

public static long MaxResponseSize { get; set; }

Gets or sets the maximum size, in bytes, of a response (time-stamp, OCSP response, CRL, downloaded document). A larger response is refused (WebException). The default value is 52428800 (50 MB).

The size of the CRLs embedded in the signatures is limited separately (MaxCrlSize of the signature classes).

public static IWebProxy Proxy { get; set; }

Gets or sets the proxy of all the requests of the library. The default value is null: the proxy of the system (the default proxy of .NET) is used.

public static int RevocationTimeout { get; set; }

Gets or sets the timeout, in milliseconds, of an OCSP request, of a CRL download and of the other downloads of the library (the time-stamp requests use TimestampSettings.ServerTimeout). The default value is 20000 (20 seconds). It is the same setting as DigitalCertificate.Timeout.

OfficeSignature class

Namespace: SignLib · Assembly: SignLib.dll

public class OfficeSignature

Signs Office Open XML documents (docx, xlsx, pptx and their macro-enabled versions) with package digital signatures compatible with Microsoft Office: XAdES signatures (the levels B, T and LT), invisible or visible (an Office signature line of a Word document), and verifies them. A document can have several signatures: a new signature does not invalidate the existing ones.

Constructors
public OfficeSignature(string librarySerialNumberLicense)

Initializes a new instance of the OfficeSignature class.

librarySerialNumberLicense
The serial number provided to register the library.
Properties
public bool AllowIncompleteValidationData { get; set; }

Gets or sets a value indicating whether a long term signature (XAdES-LT) is created even when its validation data is incomplete. The default value is false: a ValidationDataException is thrown (before the document is written) when the revocation data (OCSP response or CRL) of a certificate of the signer or of a time-stamping authority cannot be obtained (it lists the certificates and the reasons), and an InvalidOperationException when LtvLevel is None. When it is true, the signature is created with the data that could be obtained (the behaviour of the earlier versions).

public XadesCommitmentType CommitmentType { get; set; }

Gets or sets the commitment type declared by the signer (shown by Office as "Commitment type", e.g. ProofOfApproval: "Approved this document"). The default value is XadesCommitmentType.None.

public X509Certificate2 DigitalSignatureCertificate { get; set; }

Gets or sets the signing certificate (see the DigitalCertificate class).

public HashAlgorithm HashAlgorithm { get; set; }

Gets or sets the hash algorithm of the signature: SHA256 (the default), SHA384 or SHA512. It is used for the signature method, the digests of the signed parts and the digest of the signing certificate. SHA1 is not supported for new signatures (NotSupportedException).

public XadesLtvLevel LtvLevel { get; set; }

Gets or sets the revocation data included in the XAdES-LT signatures. The default value is XadesLtvLevel.IncludeOcspOnly.

public int MaxCrlSize { get; set; }

Gets or sets the maximum size, in bytes, of a CRL included in the XAdES-LT signatures: larger CRLs are skipped. The default value is 1 MB.

public string SignatureComments { get; set; }

Gets or sets the purpose of the signature (shown by Office as "Purpose for signing this document"), or null.

public OfficeSignatureLine SignatureLine { get; set; }

Gets or sets the visible signature: an Office signature line of a Word document (docx, docm). The default value is null: the signature is invisible. The visible signatures require Windows (their images are drawn with System.Drawing): on the other platforms they throw PlatformNotSupportedException.

public XadesProductionPlace SignatureProductionPlace { get; set; }

Gets or sets the place where the signature is created (xades:SignatureProductionPlace: city, state or province, postal code and country; the street address is not used by Office). The default value is null.

public XadesSignatureStandard SignatureStandard { get; set; }

Gets or sets the XAdES level of the signature. The default value is XadesSignatureStandard.XadesB. XadesT and XadesLT require TimeStamping.ServerUrl. As for the XAdES signatures, a XadesB signature is also time-stamped (XAdES-T) when TimeStamping.ServerUrl is set. XadesLTA is not supported for Office documents (NotSupportedException).

public string SignerRole { get; set; }

Gets or sets the role or the title of the signer (xades:ClaimedRole), or null.

public TimestampSettings TimeStamping { get; set; }

Gets or sets the time-stamping settings (required for the XAdES-T and XAdES-LT signatures).

Methods
public string AddSignatureLine(string inputFile, string outputFile, OfficeSignatureLine signatureLine)

Adds an unsigned signature line at the end of a Word document, for a signer who will sign it later (with this library, OfficeSignatureLinePlacement.UseExisting, or in Word). Add the signature lines of all the signers before the first signature: a document that is already signed cannot be changed (InvalidOperationException). It requires Windows (the image of the signature line is drawn with System.Drawing).

inputFile
The path of the Word document.
outputFile
The path of the document with the new signature line (it can be the input file).
signatureLine
The suggested signer, title, e-mail, signing instructions, size and alignment.

Returns. The identifier (SetupId) of the new signature line.

Exceptions.

  • FileNotFoundException: The input file does not exist.
public void ApplyDigitalSignature(Stream streamToSign)

Signs an Office document (docx, xlsx, pptx) in place: the signed document is written to the same stream.

streamToSign
The document to sign: a readable, writable and seekable stream.
public byte[] ApplyDigitalSignature(byte[] inputArray)

Signs an Office document (docx, xlsx, pptx).

inputArray
The document to sign.

Returns. The signed document.

public void ApplyDigitalSignature(string inputFile, string outputFile)

Signs an Office document (docx, xlsx, pptx). The signatures already present in the document are kept. The output file is deleted when the signature fails (unless it is the input file).

inputFile
The path of the document to sign.
outputFile
The path of the signed document (it can be the input file).

Exceptions.

  • FileNotFoundException: The input file does not exist.
  • ArgumentException: The time-stamping server is required.
  • NotSupportedException: The hash algorithm is SHA1, the level is XAdES-LTA, or a visible signature is requested for a document that is not a Word document.
  • PlatformNotSupportedException: A visible signature is requested on a platform other than Windows.
public X509Certificate2 GetDigitalSignatureCertificate(string inputFile)

Gets the signing certificate of the first signature of an Office document.

inputFile
The path of the document.

Returns. The signing certificate.

public X509Certificate2 GetDigitalSignatureCertificate(Stream inputFile)

Gets the signing certificate of the first signature of an Office document.

inputFile
The document.

Returns. The signing certificate.

public X509Certificate2 GetDigitalSignatureCertificate(string inputFile, int signatureIndex)

Gets the signing certificate of a signature of an Office document.

inputFile
The path of the document.
signatureIndex
The 0-based index of the signature.

Returns. The signing certificate.

public X509Certificate2 GetDigitalSignatureCertificate(Stream inputFile, int signatureIndex)

Gets the signing certificate of a signature of an Office document.

inputFile
The document.
signatureIndex
The 0-based index of the signature.

Returns. The signing certificate.

public int GetNumberOfSignatures(string inputFile)

Gets the number of signatures of an Office document.

inputFile
The path of the document.

Returns. The number of signatures.

public int GetNumberOfSignatures(Stream inputFile)

Gets the number of signatures of an Office document.

inputFile
The document.

Returns. The number of signatures.

public string GetSignatureAlgorithm(string inputFile)

Gets the signature algorithm of the first signature of an Office document (e.g. RSA-SHA256).

inputFile
The path of the document.

Returns. The signature algorithm.

public string GetSignatureAlgorithm(Stream inputFile)

Gets the signature algorithm of the first signature of an Office document (e.g. RSA-SHA256).

inputFile
The document.

Returns. The signature algorithm.

public string GetSignatureAlgorithm(string inputFile, int signatureIndex)

Gets the signature algorithm of a signature of an Office document (e.g. RSA-SHA256, ECDSA-SHA384).

inputFile
The path of the document.
signatureIndex
The 0-based index of the signature.

Returns. The signature algorithm.

public string GetSignatureAlgorithm(Stream inputFile, int signatureIndex)

Gets the signature algorithm of a signature of an Office document (e.g. RSA-SHA256, ECDSA-SHA384).

inputFile
The document.
signatureIndex
The 0-based index of the signature.

Returns. The signature algorithm.

public List<OfficeSignatureLineInfo> GetSignatureLines(string inputFile)

Gets the signature lines of a Word document (an empty list for the other Office documents), and whether each one is signed.

inputFile
The path of the document.

Returns. The signature lines, in document order.

public List<OfficeSignatureLineInfo> GetSignatureLines(Stream inputFile)

Gets the signature lines of a Word document (an empty list for the other Office documents), and whether each one is signed.

inputFile
The document.

Returns. The signature lines, in document order.

public List<OfficeSignatureInfo> GetSignatures(string inputFile)

Gets the signatures of an Office document and verifies them: the signer, the signing time, the time-stamp, the purpose, the signature line and the result of the verification of each signature.

inputFile
The path of the document.

Returns. The signatures, in the order of their indexes.

public List<OfficeSignatureInfo> GetSignatures(Stream inputFile)

Gets the signatures of an Office document and verifies them: the signer, the signing time, the time-stamp, the purpose, the signature line and the result of the verification of each signature.

inputFile
The document.

Returns. The signatures, in the order of their indexes.

public void SetSignaturePolicyInformation(string policyIdentifier, byte[] policyHash, string policyDigestAlgorithm, string policyUrl)

Sets the explicit signature policy of the signatures (xades:SignaturePolicyIdentifier), when a regulation or a relying party requires one. By default the policy is implied, as for the signatures created by Office.

policyIdentifier
The identifier of the policy: an OID (e.g. 2.16.724.1.3.1.1.2.1.9, with or without the urn:oid: prefix) or a URI. Null removes the policy.
policyHash
The digest of the policy document.
policyDigestAlgorithm
The digest algorithm of policyHash: an OID (e.g. 2.16.840.1.101.3.4.2.1) or a name (SHA1, SHA256, SHA384, SHA512).
policyUrl
The URL of the policy document (xades:SPURI), or null.
public bool VerifyDigitalSignature(string inputFile)

Verifies all the signatures of an Office document. The trust of the signing certificates is not verified (see DigitalCertificate.VerifyDigitalCertificate).

inputFile
The path of the document.

Returns. True if every signature is valid.

Exceptions.

  • CryptographicException: The document has no signature.
public bool VerifyDigitalSignature(Stream inputFile)

Verifies all the signatures of an Office document. The trust of the signing certificates is not verified.

inputFile
The document.

Returns. True if every signature is valid.

Exceptions.

  • CryptographicException: The document has no signature.
public bool VerifyDigitalSignature(string inputFile, int signatureIndex)

Verifies a signature of an Office document. The trust of the signing certificate is not verified.

inputFile
The path of the document.
signatureIndex
The 0-based index of the signature.

Returns. True if the signature is valid.

public bool VerifyDigitalSignature(Stream inputFile, int signatureIndex)

Verifies a signature of an Office document. The trust of the signing certificate is not verified.

inputFile
The document.
signatureIndex
The 0-based index of the signature.

Returns. True if the signature is valid.

public bool VerifyDigitalSignature(string inputFile, X509Certificate2 certificate)

Verifies that an Office document has a valid signature created with a certificate.

inputFile
The path of the document.
certificate
The certificate of the expected signer.

Returns. True if a signature of the document is valid for the certificate.

public bool VerifyDigitalSignature(Stream inputFile, X509Certificate2 certificate)

Verifies that an Office document has a valid signature created with a certificate.

inputFile
The document.
certificate
The certificate of the expected signer.

Returns. True if a signature of the document is valid for the certificate.

SecurityLimitException class

Namespace: SignLib · Assembly: SignLib.dll

public class SecurityLimitException : Exception, ISerializable

The exception thrown when a document or container exceeds a limit of SecurityLimits (e.g. a ZIP container with too many entries or a "zip bomb"), or has a structure that is refused for security reasons (e.g. duplicate entries).

Constructors
public SecurityLimitException()

Initializes a new instance of the SecurityLimitException class.

public SecurityLimitException(string message)

Initializes a new instance of the SecurityLimitException class with a message.

message
The message.
public SecurityLimitException(string message, Exception innerException)

Initializes a new instance of the SecurityLimitException class with a message and the exception that caused it.

message
The message.
innerException
The cause.

SecurityLimits static class

Namespace: SignLib · Assembly: SignLib.dll

public static class SecurityLimits

The limits applied to the documents and containers that the library reads (they may come from untrusted sources): XML documents (XAdES, XMLDSig, ASiC, Office), ZIP containers (ASiC-E) and Office packages.

Properties
public static bool AllowXmlDtd { get; set; }

Gets or sets a value indicating whether an XML document may contain a document type declaration (DTD). The default value is false: a document with a DTD is rejected. When it is true, the internal DTD is processed, but external entities and resources are never loaded, and the entity expansion is limited.

public static int MaxCompressionRatio { get; set; }

Gets or sets the maximum compression ratio (uncompressed size / compressed size) of an entry of a ZIP container or package larger than 1 MB, against "zip bombs". The default value is 1000.

public static int MaxZipEntries { get; set; }

Gets or sets the maximum number of entries of a ZIP container or package. The default value is 10000.

public static long MaxZipEntrySize { get; set; }

Gets or sets the maximum uncompressed size, in bytes, of an entry of a ZIP container or package. The default value is 1 GB.

public static long MaxZipTotalSize { get; set; }

Gets or sets the maximum total uncompressed size, in bytes, of a ZIP container or package. The default value is 2 GB.

HashAlgorithm enum

Namespace: SignLib · Assembly: SignLib.dll

public enum HashAlgorithm

Hash algorithms used to create digital signatures and time-stamp requests.

MemberValueDescription
SHA10SHA-1 (160 bits). Not recommended for new signatures: SHA-1 is no longer considered collision resistant.
SHA2561SHA-256 (256 bits). The recommended default.
SHA3842SHA-384 (384 bits).
SHA5123SHA-512 (512 bits).

SignatureLevel enum

Namespace: SignLib · Assembly: SignLib.dll

public enum SignatureLevel

The effective level of an AdES signature (ETSI baseline levels), determined from what the signature contains.

MemberValueDescription
None0Not an AdES signature (e.g. a PKCS#7 signature without the signing-certificate attribute, a XMLDSig signature without XAdES properties, a document time-stamp), or a signature that is not valid.
B1B-B: a basic AdES signature.
T2B-T: a time-stamped AdES signature.
LT3B-LT: a time-stamped AdES signature with the complete validation data (certificates and revocation data of the signer and of the time-stamping authority).
LTA4B-LTA: a B-LT signature with an archive (or document) time-stamp over its validation data.

18.2 Namespace SignLib.Pdf

TypeDescription
CustomImage classAn image added to a PDF document by PdfInsertObject.
CustomText classA text added to a PDF document by PdfInsertObject.
PdfDocumentProperties classProperties of a loaded PDF document: number of pages, certification level, file size and digital signatures.
PdfEncrypt classEncrypts PDF documents, with passwords or with a certificate.
PdfEncryptionSettings classEncryption of a PDF document signed with PdfSignature.
PdfInsertObject classAdds images, watermarks and texts to a PDF document.
PdfMerge classMerges PDF documents.
PdfSignature classDigitally signs PDF documents (PKCS#7 and PAdES signatures, with or without time-stamp and long term validation data) and adds document time-stamps.
PdfSignatureInfo classInformation about a digital signature or a document time-stamp of a PDF document.
PendingExternalSignature classA prepared PDF signature, returned by PdfSignature.PrepareExternalSignature: everything needed to complete a deferred (two-phase) external signature later, possibly in another process, hours or days afterwards, with PdfSignature.FinalizeExternalSignature.
CertifyMethod enumCertification level of a PDF document: the changes allowed after the certification signature.
FontName enumStandard PDF fonts (the 14 fonts that every PDF reader has) for the text of the visible signature.
ImagePosition enumPosition of an image relative to the content of a PDF page.
PadesLtvLevel enumRevocation data embedded in a PDF signature, for its long term validation.
PdfDocumentRestrictions enumActions allowed on an encrypted PDF document.
PdfEncryptionAlgorithm enumEncryption algorithm of a PDF document.
PdfEncryptionMethod enumEncryption method of a PDF document.
PdfSignatureStandard enumSignature format of a PDF signature.
SignatureImageType enumHow the image of a visible signature is displayed.
SignaturePosition enumPosition of the visible signature on the page.
SignatureType enumType of a signature of a PDF document.
TextAlign enumAlignment of a text relative to its starting point.
TextDirection enumDirection of a text.

CustomImage class

Namespace: SignLib.Pdf · Assembly: SignLib.dll

public class CustomImage

An image added to a PDF document by PdfInsertObject.

Constructors
public CustomImage()

Initializes a new instance of the CustomImage class.

Properties
public bool AddImageAsWatermark { get; set; }

Gets or sets a value indicating whether the image covers the entire page.

public byte[] Image { get; set; }

Gets or sets the image (e.g. the content of a JPG or PNG file).

public ImagePosition ImagePosition { get; set; }

Gets or sets the position of the image: over the content or under the content (as background).

public int PageNumber { get; set; }

Gets or sets the page of the image, or 0 for all the pages.

public Rectangle RectangePosition { get; set; }

Gets or sets the rectangle of the image on the page.

public Point StartingPointPosition { get; set; }

Gets or sets the position of the lower left corner of the image on the page.

CustomText class

Namespace: SignLib.Pdf · Assembly: SignLib.dll

public class CustomText

A text added to a PDF document by PdfInsertObject.

Constructors
public CustomText()

Initializes a new instance of the CustomText class.

Properties
public TextAlign Align { get; set; }

Gets or sets the alignment of the text relative to its starting point.

public string FontFile { get; set; }

Gets or sets the path of a TrueType font file, or null for Helvetica Bold.

public int FontSize { get; set; }

Gets or sets the font size. The default value is 12.

public int PageNumber { get; set; }

Gets or sets the page of the text, or 0 for all the pages (the default).

public Point StartingPointPosition { get; set; }

Gets or sets the starting point of the text on the page.

public string Text { get; set; }

Gets or sets the text.

public Color? TextColor { get; set; }

Gets or sets the color of the text, or null for black. (Before version 9 the type was iTextSharp.text.Color; iTextSharp is now compiled into SignLib.dll and its types are not public.)

public TextDirection TextDirection { get; set; }

Gets or sets the direction of the text. The default value is TextDirection.Normal.

PdfDocumentProperties class

Namespace: SignLib.Pdf · Assembly: SignLib.dll

public class PdfDocumentProperties

Properties of a loaded PDF document: number of pages, certification level, file size and digital signatures.

Constructors
public PdfDocumentProperties()

Initializes a new instance of the PdfDocumentProperties class.

Properties
public CertifyMethod CertificationLevel { get; }

Gets the certification level of the loaded PDF document.

public List<PdfSignatureInfo> DigitalSignatures { get; }

Gets the digital signatures and the document time-stamps of the PDF document, sorted by signing time.

public long FileSize { get; }

Gets the size of the PDF file, in bytes.

public int NumberOfPages { get; }

Gets the number of pages of the loaded PDF document.

public string Password { get; set; }

Gets or sets the password of the PDF document. A document with an unknown password cannot be signed.

Methods
public Point DocumentPageSize(int pageNumber)

Gets the size of a page of the loaded PDF document (the page rotation included).

pageNumber
The page number (1 for the first page).

Returns. The width (X) and the height (Y) of the page.

Exceptions.

  • ArgumentOutOfRangeException: The document is not loaded or the page does not exist.

PdfEncrypt class

Namespace: SignLib.Pdf · Assembly: SignLib.dll

public class PdfEncrypt

Encrypts PDF documents, with passwords or with a certificate.

Constructors
public PdfEncrypt()

Initializes a new instance of the PdfEncrypt class.

Properties
public bool AllowSignatureInvalidation { get; set; }

Gets or sets a value indicating whether a signed document is encrypted, its signatures then becoming invalid. The default value is false: PdfEncrypt.EncryptPDFFile refuses a signed document (InvalidOperationException).

public PdfDocumentRestrictions DocumentRestrictions { get; set; }

Gets or sets the actions allowed on the encrypted document (e.g. AllowPrinting | AllowFillingOfFormFields). The default value is PdfDocumentRestrictions.AllowNone.

public PdfEncryptionAlgorithm EncryptionAlgorithm { get; set; }

Gets or sets the encryption algorithm. The default value is PdfEncryptionAlgorithm.EnhancedEncryption128BitAES.

public X509Certificate2 EncryptionCertificate { get; set; }

Gets or sets the certificate used to encrypt the document (PdfEncryptionMethod.CertificateSecurity).

public PdfEncryptionMethod EncryptionMethod { get; set; }

Gets or sets the encryption method. The default value is PdfEncryptionMethod.NoEncryption.

public string LoadedDocumentPassword { get; set; }

Gets or sets the password of the loaded PDF document. A document with an unknown password cannot be encrypted.

public string OwnerPassword { get; set; }

Gets or sets the owner password: the password that allows all the actions on the document.

public string UserPassword { get; set; }

Gets or sets the user password: the password required to open the document (PdfEncryptionMethod.PasswordSecurity).

Methods
public byte[] EncryptPDFFile()

Encrypts the loaded PDF document.

Returns. The encrypted PDF document.

Exceptions.

  • NullReferenceException: The document is not loaded or the encryption certificate is not set.
  • ArgumentException: The encryption method is not set.
public void LoadPdfDocument(byte[] pdfArray)

Loads the PDF document to encrypt.

pdfArray
The PDF document.
public void LoadPdfDocument(string PdfFile)

Loads the PDF document to encrypt from a file.

PdfFile
The path of the PDF document.

Exceptions.

  • FileNotFoundException: The file does not exist.
public void LoadPdfDocument(Uri PdfUrl)

Loads the PDF document to encrypt from a URL.

PdfUrl
The URL of the PDF document.

PdfEncryptionSettings class

Namespace: SignLib.Pdf · Assembly: SignLib.dll

public class PdfEncryptionSettings

Encryption of a PDF document signed with PdfSignature. A document that is already signed cannot be encrypted.

Constructors
public PdfEncryptionSettings()

Initializes a new instance of the PdfEncryptionSettings class, without encryption.

Properties
public PdfDocumentRestrictions DocumentRestrictions { get; set; }

Gets or sets the actions allowed on the encrypted document (e.g. AllowPrinting | AllowFillingOfFormFields). The default value is PdfDocumentRestrictions.AllowNone.

public PdfEncryptionAlgorithm EncryptionAlgorithm { get; set; }

Gets or sets the encryption algorithm. The default value is PdfEncryptionAlgorithm.EnhancedEncryption128BitAES.

public X509Certificate2 EncryptionCertificate { get; set; }

Gets or sets the certificate used to encrypt the document (PdfEncryptionMethod.CertificateSecurity).

public PdfEncryptionMethod EncryptionMethod { get; set; }

Gets or sets the encryption method. The default value is PdfEncryptionMethod.NoEncryption.

public string OwnerPassword { get; set; }

Gets or sets the owner password: the password that allows all the actions on the document.

public string UserPassword { get; set; }

Gets or sets the user password: the password required to open the document (PdfEncryptionMethod.PasswordSecurity).

PdfInsertObject class

Namespace: SignLib.Pdf · Assembly: SignLib.dll

public class PdfInsertObject

Adds images, watermarks and texts to a PDF document.

Constructors
public PdfInsertObject()

Initializes a new instance of the PdfInsertObject class.

Properties
public bool AllowSignatureInvalidation { get; set; }

Gets or sets a value indicating whether the objects are inserted in a signed document, whose signatures then become invalid. The default value is false: PdfInsertObject.InsertObjects refuses a signed document (InvalidOperationException).

public PdfDocumentProperties DocumentProperties { get; set; }

Gets or sets the properties of the loaded PDF document (number of pages, digital signatures, password).

Methods
public void AddImage(byte[] image, int pageNumber, ImagePosition imagePostition)

Adds an image that covers the entire page (e.g. a watermark) to the PDF document.

image
The image (e.g. the content of a JPG or PNG file).
pageNumber
The page of the image, or 0 for all the pages.
imagePostition
The position of the image: over the content or under the content (as background).
public void AddImage(byte[] image, Rectangle imageLocation, int pageNumber, ImagePosition imagePostition)

Adds an image, in a rectangle, to the PDF document.

image
The image (e.g. the content of a JPG or PNG file).
imageLocation
The rectangle of the image on the page.
pageNumber
The page of the image, or 0 for all the pages.
imagePostition
The position of the image: over the content or under the content (as background).
public void AddImage(byte[] image, Point imageLocation, int pageNumber, ImagePosition imagePostition)

Adds an image, at its original size, to the PDF document.

image
The image (e.g. the content of a JPG or PNG file).
imageLocation
The position of the lower left corner of the image on the page.
pageNumber
The page of the image, or 0 for all the pages.
imagePostition
The position of the image: over the content or under the content (as background).
public void AddText(CustomText customText)

Adds a text to the PDF document.

customText
The text and its properties.
public byte[] InsertObjects()

Adds the images and the texts to the PDF document.

Returns. The PDF document with the images and the texts.

Exceptions.

  • NullReferenceException: The document is not loaded.
public void LoadPdfDocument(byte[] pdfArray)

Loads the PDF document.

pdfArray
The PDF document.
public void LoadPdfDocument(string PdfFile)

Loads the PDF document from a file.

PdfFile
The path of the PDF document.

Exceptions.

  • FileNotFoundException: The file does not exist.
public void LoadPdfDocument(Uri PdfUrl)

Loads the PDF document from a URL.

PdfUrl
The URL of the PDF document.

PdfMerge class

Namespace: SignLib.Pdf · Assembly: SignLib.dll

public class PdfMerge

Merges PDF documents.

Methods
public static byte[] MergePdfFiles(List<byte[]> sourceFiles)

Merges PDF documents into a single one. The metadata (title, author, subject, keywords and creator) of the merged document are taken from the first document.

sourceFiles
The PDF documents, in the order in which their pages are added to the merged document.

Returns. The merged PDF document.

PdfSignature class

Namespace: SignLib.Pdf · Assembly: SignLib.dll

public class PdfSignature

Digitally signs PDF documents (PKCS#7 and PAdES signatures, with or without time-stamp and long term validation data) and adds document time-stamps.

Constructors
public PdfSignature(string librarySerialNumberLicense)

Initializes a new instance of the PdfSignature class.

librarySerialNumberLicense
The serial number provided to register the library.
Properties
public bool AllowIncompleteValidationData { get; set; }

Gets or sets a value indicating whether a PAdES-LT or PAdES-LTA signature is created even when its validation data is incomplete. The default value is false: a ValidationDataException is thrown when the revocation data (OCSP response or CRL) of a certificate of the signer or of the time-stamping authority cannot be obtained (it lists the certificates and the reasons);an InvalidOperationException is thrown when PdfSignature.PadesLtvLevel is PadesLtvLevel.None or when no time-stamping server is set (a PAdES-LT signature is a time-stamped signature with its validation data). When it is true, the signature is created with the data that could be obtained (the behaviour of the earlier versions).

public CertifyMethod CertifySignature { get; set; }

Gets or sets the certification level of the signature. The default value is CertifyMethod.NotCertified.

public X509Certificate2 DigitalSignatureCertificate { get; set; }

Gets or sets the signing certificate (see the DigitalCertificate class).

public PdfDocumentProperties DocumentProperties { get; set; }

Gets or sets the properties of the loaded PDF document (number of pages, digital signatures, password).

public PdfEncryptionSettings Encryption { get; set; }

Gets or sets the encryption of the signed document.

public string FontFile { get; set; }

Gets or sets the path of a TrueType font file for the text of the visible signature (e.g. "C:\\WINDOWS\\FONTS\\times.TTF"). When it is set, PdfSignature.FontName is not used.

public FontName FontName { get; set; }

Gets or sets the standard PDF font of the text of the visible signature. The default font is Helvetica.

public int FontSize { get; set; }

Gets or sets the font size of the text of the visible signature.

public HashAlgorithm HashAlgorithm { get; set; }

Gets or sets the hash algorithm of the signature. The default value is SHA256.

public bool OldStyleAdobeSignature { get; set; }

Gets or sets a value indicating whether the visible signature uses the old Adobe Acrobat style (a question mark for the unknown signatures, a check mark for the valid ones). The default value is false.

public PadesLtvLevel PadesLtvLevel { get; set; }

Gets or sets the revocation data embedded in the signature for its long term validation. The default value is PadesLtvLevel.IncludeOcspOnly.

public Rectangle SignatureAdvancedPosition { set; }

Sets the rectangle of the visible signature on the page (instead of PdfSignature.SignaturePosition).

public bool SignatureAppearsOnAllPages { get; set; }

Gets or sets a value indicating whether the visible signature appears on all the pages, once on each page. The default value is false.

public byte[] SignatureImage { get; set; }

Gets or sets the image of the visible signature (e.g. the content of a JPG or PNG file).

public SignatureImageType SignatureImageType { get; set; }

Gets or sets how the image of the visible signature is displayed. The default value is SignatureImageType.ImageAndText.

public int SignaturePage { get; set; }

Gets or sets the page of the visible signature. The default value is 1; int.MaxValue means the last page. The signature rectangle is computed on this page, also when the signature appears on several pages.

public List<int> SignaturePages { get; set; }

Gets or sets the pages on which the visible signature appears, instead of PdfSignature.SignaturePage. The page numbers start at 1 and int.MaxValue means the last page; a page listed more than once gets a single signature. The signature rectangle is the same on every page. Ignored when PdfSignature.SignatureAppearsOnAllPages is true. The default value is an empty list (null is the same).

public SignaturePosition SignaturePosition { get; set; }

Gets or sets the position of the visible signature on the page. The default value is SignaturePosition.TopRight.

public PdfSignatureStandard SignatureStandard { get; set; }

Gets or sets the signature format. The default value is PdfSignatureStandard.Default (PKCS#7), which is recognized by the older PDF readers.

public string SignatureText { get; set; }

Gets or sets the text of the visible signature, instead of the default text (the signer name, the signing time, the reason and the location).

public string SigningApplicationName { get; set; }

Gets or sets the name of the application that creates the signature (e.g. "My Application"). It is written in the signature build properties (/Prop_Build /App /Name) of the signatures and of the document time-stamps, and Adobe Reader shows it in the advanced signature properties as "Signature was created using [name] [version]". The default value is null: nothing is written and Adobe Reader shows "Not available". At most 127 bytes in UTF-8 encoding.

Exceptions.

  • ArgumentException: The name is too long or it contains control characters.
public string SigningApplicationVersion { get; set; }

Gets or sets the version of the application that creates the signature (e.g. "8.0.1"), written in the signature build properties (/Prop_Build /App /REx) and shown by Adobe Reader after the application name. It is used only when PdfSignature.SigningApplicationName is set. The default value is null.

public string SigningLocation { get; set; }

Gets or sets the signing location.

public string SigningReason { get; set; }

Gets or sets the signing reason.

public TextDirection TextDirection { set; }

Sets the direction of the text of the visible signature. The default value is TextDirection.Normal.

public TimestampSettings TimeStamping { get; set; }

Gets or sets the time-stamping settings. When the server URL is set, the signatures are time-stamped.

public bool VisibleSignature { get; set; }

Gets or sets a value indicating whether the signature is visible on the document. The default value is true.

Methods
public byte[] AddArchiveTimestamp()

Renews the long term archival (PAdES-LTA) of the loaded signed document: adds to the document security store the validation data of all its signatures and document time-stamps (in particular of the time-stamping authority of the last document time-stamp, which was not in the store), then a new document time-stamp. Call it periodically, before the certificate of the time-stamping authority of the last document time-stamp expires (see LongTermArchive.GetPdfRenewalDate) or its algorithms become weak. The signing certificate is not needed; PadesLtvLevel, MaxCrlSize, AllowIncompleteValidationData and TimeStamping are used.

Returns. The document with the new validation data and document time-stamp.

Exceptions.

  • NullReferenceException: The document is not loaded or the time-stamping server is not set.
  • InvalidOperationException: The document is not signed, or PadesLtvLevel is None.
  • CryptographicException: A signature or a document time-stamp of the document is not valid.
  • ValidationDataException: Some revocation data cannot be obtained (unless AllowIncompleteValidationData is set).
  • CertificateRevokedException: A certificate is revoked.
public void AddArchiveTimestamp(Stream output)

Renews the long term archival of the loaded document, as PdfSignature.AddArchiveTimestamp, and writes the document to a stream. With a document loaded from a stream (PdfSignature.LoadPdfDocument), the document is not held in memory: it is copied from its stream to output, followed by the new revisions.

output
The stream that receives the document. It is not closed.
public byte[] ApplyDigitalSignature()

Signs the loaded PDF document.

Returns. The signed PDF document.

Exceptions.

public byte[] ApplyDigitalSignature(string signatureField)

Signs the loaded PDF document.

signatureField
The name of an existing empty signature field to sign, or null for a new signature field.

Returns. The signed PDF document.

Exceptions.

public void ApplyDigitalSignature(Stream output)

Signs the loaded PDF document and writes the signed document to a stream. With a document loaded from a stream (PdfSignature.LoadPdfDocument), the document is not held in memory: it is copied from its stream to output, followed by the new revision.

output
The stream that receives the signed document. It is not closed.

Exceptions.

public void ApplyDigitalSignature(string signatureField, Stream output)

Signs the loaded PDF document and writes the signed document to a stream. With a document loaded from a stream (PdfSignature.LoadPdfDocument), the document is not held in memory: it is copied from its stream to output, followed by the new revision.

signatureField
The name of an existing empty signature field to sign, or null for a new signature field.
output
The stream that receives the signed document. It is not closed.

Exceptions.

public byte[] ApplyTimestampSignature()

Adds a document time-stamp (ETSI.RFC3161) to the loaded PDF document.

Returns. The time-stamped PDF document.

Exceptions.

  • NullReferenceException: The document is not loaded or the time-stamping server is not set.
public void ApplyTimestampSignature(Stream output)

Adds a document time-stamp (ETSI.RFC3161) to the loaded PDF document and writes the document to a stream. With a document loaded from a stream (PdfSignature.LoadPdfDocument), the document is not held in memory: it is copied from its stream to output, followed by the new revision.

output
The stream that receives the document. It is not closed.

Exceptions.

  • NullReferenceException: The document is not loaded or the time-stamping server is not set.
public byte[] FinalizeExternalSignature(PendingExternalSignature pending, byte[] externalSignatureBytes)

Phase 2 of a deferred external signature: completes the CMS signature with the signature value created by the external signer and inserts it in the PDF document prepared by PdfSignature.PrepareExternalSignature. No private key is needed. When TimestampSettings.ServerUrl is set on this instance, the signature is time-stamped; PAdES-LT and PAdES-LTA (from the prepared signature) are completed afterwards.

pending
The prepared signature returned by PrepareExternalSignature.
externalSignatureBytes
The signature value created by the external signer over pending.DataToSign, with the hash algorithm pending.DigestAlgorithmOid (what IExternalSignature.ApplySignature returns).

Returns. The signed PDF document.

Exceptions.

  • CryptographicException: The signature does not fit in the space reserved for it.
public void LoadPdfDocument(byte[] pdfArray)

Loads the PDF document to sign.

pdfArray
The PDF document.
public void LoadPdfDocument(Stream pdfStream)

Loads the PDF document to sign from a stream, without copying it into memory: for large documents. The signature is then written with PdfSignature.ApplyDigitalSignature: the document is copied from this stream to the output, followed by the new revision (the signature and, for PAdES-LT and PAdES-LTA, the validation data and the document time-stamp), which is the only part held in memory.

The stream is read from its current position to its end; it must stay open and unchanged until the document is signed. A stream that is not seekable is copied into memory first. The document is also copied into memory when it cannot be signed incrementally from the stream: bytes before the PDF header, a damaged cross-reference table, a signature without append mode (encryption, PdfSignature.AppendSignature false), the demo version of the library on a document not signed yet, and the deferred external signatures (PdfSignature.PrepareExternalSignature). The documents of 2 GB or more are not supported.

pdfStream
The PDF document.

Exceptions.

  • IOException: The document is larger than 2 GB.
public void LoadPdfDocument(string PdfFile)

Loads the PDF document to sign from a file.

PdfFile
The path of the PDF document.

Exceptions.

  • FileNotFoundException: The file does not exist.
public void LoadPdfDocument(Uri PdfUrl)

Loads the PDF document to sign from a URL.

PdfUrl
The URL of the PDF document.
public PendingExternalSignature PrepareExternalSignature(string signatureField)

Phase 1 of a deferred external signature: prepares the PDF document exactly as ApplyDigitalSignature does and computes the data to sign, without signing it (no private key is used and no external signature provider is called). The result contains everything needed to complete the signature later, even in another process, with PdfSignature.FinalizeExternalSignature.

signatureField
The name of an existing empty signature field to sign, or null for a new signature field.

Returns. The prepared signature.

Exceptions.

public static byte[] RepairPdf(byte[] pdfContent)

Tries to repair a damaged PDF document, by rebuilding it.

pdfContent
The PDF document.

Returns. The rebuilt PDF document.

public static byte[] RepairPdf(string pdfFile)

Tries to repair a damaged PDF document, by rebuilding it.

pdfFile
The path of the PDF document.

Returns. The rebuilt PDF document.

public void SetSignaturePolicyInformation(string policyIdentifier, byte[] policyHash, string policyDigestAlgorithm, string policyUrl)

Sets the explicit signature policy (the signature-policy-identifier signed attribute) of the signatures created with this instance. By default there is no policy.

policyIdentifier
The OID of the policy (e.g. 2.16.76.1.7.1.5.2.3), or null to remove the policy.
policyHash
The hash of the policy document.
policyDigestAlgorithm
The OID of the hash algorithm of the policy document (e.g. 2.16.840.1.101.3.4.2.1).
policyUrl
The URL of the policy document (e.g. http://ca.signfiles.com/CaPolicy.html), or null.

PdfSignatureInfo class

Namespace: SignLib.Pdf · Assembly: SignLib.dll

public class PdfSignatureInfo

Information about a digital signature or a document time-stamp of a PDF document.

Constructors
public PdfSignatureInfo()

Initializes a new instance of the PdfSignatureInfo class.

Properties
public bool CoversWholeDocument { get; }

Gets a value indicating whether the signature covers the whole file, up to its end. It is false when the file was changed after the signature (e.g. by a later signature or an incremental update): the signature can be valid, and the later changes are not covered by it.

public string DigestAlgorithm { get; }

Gets the algorithm of the signature (e.g. SHA256withRSA or SHA256withECDSA).

public string HashAlgorithm { get; }

Gets the hash algorithm of the signature (e.g. SHA256).

public SignatureLevel Level { get; }

Gets the effective level of the signature (B, T, LT, LTA), determined from what it contains; None for a signature that is not an AdES signature or that is not valid.

public IReadOnlyList<MissingValidationData> MissingValidationData { get; }

Gets the certificates without validation data in the signature (empty when ValidationDataComplete is true).

public string SignatureAlgorithm { get; }

Gets the algorithm of the key of the signing certificate (RSA, DSA or ECC).

public bool SignatureAlgorithmNotSupported { get; }

Gets a value indicating whether the signature algorithm or the digest algorithm of the signature is not supported by the library. The signature could not be verified: PdfSignatureInfo.SignatureIsValid is false, but the signature was not found altered.

public byte[] SignatureBytes { get; }

Gets the signature, as an encoded PKCS#7 (CMS) signed message.

public X509Certificate2 SignatureCertificate { get; }

Gets the signing certificate.

public byte[] SignatureHash { get; }

Gets the signature value of the signer.

public bool SignatureIsTimestamped { get; }

Gets a value indicating whether the signature is time-stamped: it has a time-stamp whose message imprint is the hash of the signature value and whose signature is valid. A time-stamp that does not belong to this signature (e.g. copied from another signature) is not counted; it is in PdfSignatureInfo.TimestampInfo, with TimestampInfo.IsTimestampAltered true.

public bool SignatureIsValid { get; }

Gets a value indicating whether the signature is valid. Use it with caution: only the integrity of the signature is verified, not the certificate chain or the revocation status of the signing certificate. The byte range of the signature must be well formed (two ranges [0 a b c], the gap being exactly the /Contents value), and the signing certificate must be the one named by the signing-certificate attribute, when the signature has it. For a document time-stamp, the message imprint must be the hash of the byte range.

public string SignatureName { get; }

Gets the name of the signature field.

public DateTime SignatureTime { get; }

Gets the signing time: the time of the time-stamp when the signature is time-stamped, otherwise the time declared by the signer.

public SignatureType SignatureType { get; }

Gets the type of the signature: a digital signature or a document time-stamp.

public string SigningLocation { get; }

Gets the signing location.

public string SigningReason { get; }

Gets the signing reason.

public TimestampInfo TimestampInfo { get; }

Gets the information about the time-stamp of the signature, or null.

public bool ValidationDataComplete { get; }

Gets a value indicating whether the signature contains the complete validation data: an OCSP response or a CRL for every certificate (except the root) of the chains of the signer and of the time-stamping authority of the signature time-stamp, valid at the time of the time-stamp.

PendingExternalSignature class

Namespace: SignLib.Pdf · Assembly: SignLib.dll

public class PendingExternalSignature

A prepared PDF signature, returned by PdfSignature.PrepareExternalSignature: everything needed to complete a deferred (two-phase) external signature later, possibly in another process, hours or days afterwards, with PdfSignature.FinalizeExternalSignature. No value depends on a live iTextSharp object or on a private key, so the object can be serialized (e.g. as JSON) and stored. Do not use BinaryFormatter for this.

Properties
public byte[][] CertificateChainRawData { get; set; }

Gets or sets the certificate chain (from the signing certificate to the root), DER encoded.

public int ContentsByteBlockSize { get; set; }

Gets or sets the size, in bytes, reserved for the CMS signature (before the hexadecimal encoding).

public int ContentsPosition { get; set; }

Gets or sets the position, in bytes, of the /Contents placeholder in PendingExternalSignature.PendingDocument.

public int ContentsPosLength { get; set; }

Gets or sets the length, in bytes, of the hexadecimal /Contents placeholder.

public string ContentTypeOid { get; set; }

Gets or sets the OID of the content type of the CMS signature.

public byte[] DataToSign { get; set; }

Gets or sets the data that the external signer must hash and sign: the DER encoded CMS signed attributes (not the PDF content and not a hash), exactly what IExternalSignature.ApplySignature receives.

public string DigestAlgorithmOid { get; set; }

Gets or sets the OID of the hash algorithm that the external signer must use (e.g. SHA-256).

public string DigestOid { get; set; }

Gets or sets the OID of the digest algorithm of the CMS signer.

public bool Encapsulate { get; set; }

Gets or sets a value indicating whether the content is encapsulated in the CMS signature (false for the PDF signatures).

public string EncryptionOid { get; set; }

Gets or sets the OID of the signature algorithm of the CMS signer.

public byte[] PendingDocument { get; set; }

Gets or sets the prepared PDF document: with the final /ByteRange and an empty /Contents placeholder of the reserved size. It is not a valid signed PDF until it is completed by FinalizeExternalSignature.

public string SignatureFieldName { get; set; }

Gets or sets the name of the signature field: FinalizeExternalSignature uses it to find this signature among the signatures of the document for PAdES-LT and PAdES-LTA.

public PdfSignatureStandard SignatureStandard { get; set; }

Gets or sets the signature format.

public byte[] SignedContent { get; set; }

Gets or sets the signed PDF bytes (the /ByteRange content) covered by the message digest of PendingExternalSignature.DataToSign.

public byte[] SigningCertificateRawData { get; set; }

Gets or sets the signing certificate (public data only).

CertifyMethod enum

Namespace: SignLib.Pdf · Assembly: SignLib.dll

public enum CertifyMethod

Certification level of a PDF document: the changes allowed after the certification signature.

MemberValueDescription
NotCertified0The document is not certified.
NoChangesAllowed1No changes are allowed.
FormFilling2Filling the form fields (and signing) is allowed.
AnnotationsAndFormFilling3Adding annotations and filling the form fields (and signing) are allowed.

FontName enum

Namespace: SignLib.Pdf · Assembly: SignLib.dll

public enum FontName

Standard PDF fonts (the 14 fonts that every PDF reader has) for the text of the visible signature.

MemberValueDescription
Helvetica0Helvetica.
Helvetica_Bold1Helvetica Bold.
Helvetica_Oblique2Helvetica Oblique.
Helvetica_BoldOblique3Helvetica Bold Oblique.
Courier4Courier.
Courier_Bold5Courier Bold.
Courier_Oblique6Courier Oblique.
Courier_BoldOblique7Courier Bold Oblique.
Times_Roman8Times Roman.
Times_Bold9Times Bold.
Times_Italic10Times Italic.
Times_BoldItalic11Times Bold Italic.

ImagePosition enum

Namespace: SignLib.Pdf · Assembly: SignLib.dll

public enum ImagePosition

Position of an image relative to the content of a PDF page.

MemberValueDescription
ImageUnderContent0The image is inserted under the content of the page (as background).
ImageOverContent1The image is inserted over the content of the page.

PadesLtvLevel enum

Namespace: SignLib.Pdf · Assembly: SignLib.dll

public enum PadesLtvLevel

Revocation data embedded in a PDF signature, for its long term validation.

MemberValueDescription
None0No revocation data.
IncludeCrl1The CRLs of the certificate chain, when available.
IncludeCrlAndOcsp2The CRLs of the certificate chain and the OCSP responses of the signing certificate and of its issuer, when available.
IncludeOcspOnly3The OCSP response of the signing certificate, when available (otherwise its CRL, so that the signature is not left without revocation data), and the CRLs of the CA certificates.

PdfDocumentRestrictions enum

Namespace: SignLib.Pdf · Assembly: SignLib.dll

public enum PdfDocumentRestrictions

Actions allowed on an encrypted PDF document. The values can be combined (e.g. AllowPrinting | AllowFillingOfFormFields).

MemberValueDescription
AllowNone0No action is allowed.
AllowContentCopying16Allows copying the content.
AllowFillingOfFormFields256Allows filling the form fields.
AllowContentCopyingForAccessibility512Allows copying the content for accessibility.
AllowDocumentAssembly1024Allows the assembly of the document (inserting, rotating or deleting pages).
AllowPrinting2052Allows printing.

PdfEncryptionAlgorithm enum

Namespace: SignLib.Pdf · Assembly: SignLib.dll

public enum PdfEncryptionAlgorithm

Encryption algorithm of a PDF document. The 256-bit AES encryption of PDF 2.0 (ISO 32000-2, revision 6) is not supported.

MemberValueDescription
StandardEncryption40BitRC4040-bit RC4 (revision 2). Insecure: it is easily broken. Deprecated by ISO 32000-2 (PDF 2.0); use it only for very old PDF readers.
StandardEncryption128BitRC41128-bit RC4 (revision 3). Weak. Deprecated by ISO 32000-2 (PDF 2.0).
EnhancedEncryption128BitAES2128-bit AES (revision 4). The strongest supported algorithm and the recommended one; it is opened by all current PDF readers.

PdfEncryptionMethod enum

Namespace: SignLib.Pdf · Assembly: SignLib.dll

public enum PdfEncryptionMethod

Encryption method of a PDF document.

MemberValueDescription
CertificateSecurity0The document is encrypted for a certificate: it can be opened only where the private key of the certificate is available.
PasswordSecurity1The document is encrypted with passwords.
NoEncryption2The document is not encrypted.

PdfSignatureStandard enum

Namespace: SignLib.Pdf · Assembly: SignLib.dll

public enum PdfSignatureStandard

Signature format of a PDF signature.

MemberValueDescription
Default0PKCS#7 (adbe.pkcs7.detached), recognized by the older PDF readers.
Pades1PAdES baseline (ETSI.CAdES.detached, ETSI EN 319 142-1), recognized by Adobe Reader X and later.
PadesLT2PAdES with long term validation data (PAdES-B-LT): the certificates and the revocation data are added to the document security store.
PadesLTA3PAdES for long term archival (PAdES-B-LTA): PAdES-LT followed by a document time-stamp.

SignatureImageType enum

Namespace: SignLib.Pdf · Assembly: SignLib.dll

public enum SignatureImageType

How the image of a visible signature is displayed.

MemberValueDescription
ImageAsBackground0The image is the background of the signature text.
ImageWithNoText1Only the image is displayed.
ImageAndText2The image is displayed on the left and the signature text on the right.

SignaturePosition enum

Namespace: SignLib.Pdf · Assembly: SignLib.dll

public enum SignaturePosition

Position of the visible signature on the page.

MemberValueDescription
TopRight0The top right corner of the page.
TopMiddle1The top middle of the page.
TopLeft2The top left corner of the page.
BottomRight3The bottom right corner of the page.
BottomMiddle4The bottom middle of the page.
BottomLeft5The bottom left corner of the page.

SignatureType enum

Namespace: SignLib.Pdf · Assembly: SignLib.dll

public enum SignatureType

Type of a signature of a PDF document.

MemberValueDescription
DigitalSignature0A digital signature.
TimestampSignature1A document time-stamp (RFC 3161).

TextAlign enum

Namespace: SignLib.Pdf · Assembly: SignLib.dll

public enum TextAlign

Alignment of a text relative to its starting point.

MemberValueDescription
Left0The text starts at the starting point.
Right1The text ends at the starting point.
Center2The text is centered on the starting point.

TextDirection enum

Namespace: SignLib.Pdf · Assembly: SignLib.dll

public enum TextDirection

Direction of a text.

MemberValueDescription
Normal0Left to right.
RightToLeft1Right to left.

18.3 Namespace SignLib.Cades

TypeDescription
CadesSignature classCreates CMS / PKCS#7 and CAdES signatures of any document, attached or detached, with an optional time-stamp and long term validation data.
CadesSignatureInfo classA signer of a CMS / CAdES signature verified by CadesVerify.
CadesVerify classVerifies a CMS / PKCS#7 or CAdES signature (attached or detached, binary or Base64 encoded) and gets the information about its signers.
CadesLtvLevel enumThe revocation data included in the long term CAdES signatures (CAdES-C, CAdES-X Long, CAdES-A, CAdES-LT and CAdES-LTA), for the certificate chains of the signer and of the time-stamping authority (the roots excepted).
CadesSignatureStandard enumThe format of the signatures created by CadesSignature.

CadesSignature class

Namespace: SignLib.Cades · Assembly: SignLib.dll

public class CadesSignature

Creates CMS / PKCS#7 and CAdES signatures of any document, attached or detached, with an optional time-stamp and long term validation data. When the signed data is itself a CMS signature, the new signature is added to it (co-signature).

Constructors
public CadesSignature(string librarySerialNumberLicense)

Initializes a new instance of the CadesSignature class.

librarySerialNumberLicense
The serial number provided to register the library.
Properties
public bool AllowIncompleteValidationData { get; set; }

Gets or sets a value indicating whether a long term signature (CAdES-C, CAdES-X Long, CAdES-A, CAdES-LT and CAdES-LTA) is created even when the revocation data (OCSP response or CRL) of a certificate of the signer or of the time-stamping authority cannot be obtained. The default value is false: a ValidationDataException is thrown, which lists the certificates and the reasons. When it is true, the signature is created with the data that could be obtained (the behaviour of the earlier versions).

public bool CoSignExistingSignature { get; set; }

Gets or sets a value indicating whether data that is a CMS signature (e.g. a .p7s or .p7m file) is co-signed: a new signer is added to the existing signature, which keeps its signers, certificates, CRLs, OCSP responses and content. The default value is true. When it is false, the data is always signed as a document (a CMS signature is then signed as a file, like any other).

When an existing signature is co-signed, the new signature keeps its packaging: it encapsulates the content when the existing signature does, and it is detached when the existing signature is detached (the content is then given to CadesSignature.ApplyDigitalSignature). CadesSignature.IsDetachedSignature applies only to the signature of a document.

public X509Certificate2 DigitalSignatureCertificate { get; set; }

Gets or sets the signing certificate (see the DigitalCertificate class).

public HashAlgorithm HashAlgorithm { get; set; }

Gets or sets the hash algorithm of the signature. The default value is SHA256.

public bool IsDetachedSignature { get; set; }

Gets or sets a value indicating whether the signature is detached: the signed document is not included in the signature. The default value is false.

public CadesLtvLevel LtvLevel { get; set; }

Gets or sets the revocation data included in the long term signatures (CAdES-C, CAdES-X Long, CAdES-A, CAdES-LT and CAdES-LTA). The default value is CadesLtvLevel.IncludeOcspOnly: the OCSP response of the signing certificate (its CRL only when the OCSP responder does not answer) and the CRLs of the CA certificates. The downloaded data is reused by the next signatures (see RevocationCache).

public int MaxCrlSize { get; set; }

Gets or sets the maximum size, in bytes, of a CRL included in the long term validation data: larger CRLs are skipped. The default value is 20 MB.

public string MimeType { get; set; }

Gets or sets the media type of the signed document (e.g. text/plain), written in the mime-type signed attribute of CadesSignatureStandard.CadesLT and CadesSignatureStandard.CadesLTA signatures. When it is not set, the media type is inferred from the extension of the file given to CadesSignature.ApplyDigitalSignature (application/octet-stream for an unknown extension), and the attribute is not added when signing data (CadesSignature.ApplyDigitalSignature) or when co-signing an existing signature.

public CadesSignatureStandard SignatureStandard { get; set; }

Gets or sets the signature format. The default value is CadesSignatureStandard.CadesBes.

public TimestampSettings TimeStamping { get; set; }

Gets or sets the time-stamping settings. When the server URL is set, the signatures are time-stamped.

Methods
public byte[] AddArchiveTimestamp(byte[] signature, byte[] detachedContent = null)

Renews the long term archival of a CAdES-LTA signature (ETSI EN 319 122-1, 5.5.3): adds to the SignedData the validation data of the time-stamping authority of the last archive time-stamp of each CAdES-LTA signer, then a new archive-time-stamp-v3, which covers the previous ones. Call it periodically, before the certificate of the time-stamping authority of the last archive time-stamp expires (see LongTermArchive.GetCadesRenewalDate) or its algorithms become weak. The signing certificate is not needed; LtvLevel, MaxCrlSize, AllowIncompleteValidationData and TimeStamping are used.

signature
The CAdES-LTA signature.
detachedContent
The signed document of a detached signature, otherwise null.

Returns. The signature with the new validation data and archive time-stamp.

Exceptions.

  • NullReferenceException: The time-stamping server is not set.
  • InvalidOperationException: The signature has no CAdES-LTA signer.
  • CryptographicException: The signature of a CAdES-LTA signer is not valid.
  • ValidationDataException: Some revocation data cannot be obtained (unless AllowIncompleteValidationData is set).
  • CertificateRevokedException: A certificate is revoked.
public byte[] ApplyDigitalSignature(string inputFile)

Signs a file.

inputFile
The path of the file to sign, or of a CMS signature to co-sign.

Returns. The signature (with the file, unless the signature is detached).

Exceptions.

  • FileNotFoundException: The file does not exist.
  • CryptographicException: The signature cannot be created.
public byte[] ApplyDigitalSignature(byte[] unsignedArray)

Signs data.

unsignedArray
The data to sign, or a CMS signature to co-sign.

Returns. The signature (with the data, unless the signature is detached).

Exceptions.

  • CryptographicException: The signature cannot be created.
public void ApplyDigitalSignature(Stream input, Stream output)

Signs the content of a stream and writes the signature to another stream, without holding the content in memory: for large documents. The content is read once to compute its digests. A detached signature (CadesSignature.IsDetachedSignature) is then written to output; an attached signature (.p7m) is written with the content, read a second time from input. All the formats are supported (CMS, CAdES-BES to CAdES-LTA). The stream is always signed as a document: to co-sign an existing CMS signature, use CadesSignature.ApplyDigitalSignature.

input
The content to sign, read from its current position to its end. An attached signature needs a seekable stream (CanSeek), which is read twice; a stream that is not seekable is then copied into memory first. A detached signature reads any stream once.
output
The stream that receives the signature. It is not closed.

Exceptions.

  • CryptographicException: The signature cannot be created.
public byte[] ApplyDigitalSignature(byte[] signature, byte[] detachedContent)

Co-signs a detached CMS signature: a new signer is added to the signature, which keeps its signers, certificates, CRLs and OCSP responses. The new signature is detached too.

signature
The detached CMS signature.
detachedContent
The content signed by the existing signature.

Returns. The co-signed detached signature.

Exceptions.

  • CryptographicException: The signature cannot be created, or the content is not the content signed by the existing signature.
public void SetSignaturePolicyInformation(string policyIdentifier, byte[] policyHash, string policyDigestAlgorithm, string policyUrl)

Sets the explicit signature policy (the signature-policy-identifier signed attribute) of the signatures created with this instance. By default there is no policy.

policyIdentifier
The OID of the policy (e.g. 2.16.76.1.7.1.5.2.3), or null to remove the policy.
policyHash
The hash of the policy document.
policyDigestAlgorithm
The OID of the hash algorithm of the policy document (e.g. 2.16.840.1.101.3.4.2.1).
policyUrl
The URL of the policy document (e.g. http://ca.signfiles.com/CaPolicy.html), or null.

CadesSignatureInfo class

Namespace: SignLib.Cades · Assembly: SignLib.dll

public class CadesSignatureInfo

A signer of a CMS / CAdES signature verified by CadesVerify.

Properties
public Oid HashAlgorithm { get; }

Gets the hash algorithm of the signature (e.g. SHA256).

public SignatureLevel Level { get; }

Gets the effective level of the signature (B, T, LT, LTA), determined from what it contains; None for a signature that is not an AdES signature or that is not valid.

public IReadOnlyList<MissingValidationData> MissingValidationData { get; }

Gets the certificates without validation data in the signature (empty when ValidationDataComplete is true).

public bool SignatureAlgorithmNotSupported { get; }

Gets a value indicating whether the signature algorithm or the digest algorithm of the signature is not supported by the library. The signature could not be verified: CadesSignatureInfo.SignatureIsValid is false, but the signature was not found altered.

public X509Certificate2 SignatureCertificate { get; }

Gets the signing certificate, or null when the signature does not contain it.

public byte[] SignatureHash { get; }

Gets the signature value.

public bool SignatureIsTimestamped { get; }

Gets a value indicating whether the signature is time-stamped: it has a time-stamp whose message imprint is the hash of the signature value and whose signature is valid. A time-stamp that does not belong to this signature is not counted; it is in CadesSignatureInfo.TimestampInfo, with TimestampInfo.IsTimestampAltered true.

public bool SignatureIsValid { get; }

Gets a value indicating whether the signature is valid: the signed data was not changed and the signature value matches the signing certificate, which is the one named by the signing-certificate attribute when the signature has it. The certificate itself (chain, validity, revocation) is not verified.

public CadesSignatureStandard SignatureStandard { get; }

Gets the format of this signer, detected from its attributes (CMS, CAdES-BES, CAdES-T, CAdES-LT, CAdES-LTA...).

A CAdES-BES signature with the signature time-stamp is CadesSignatureStandard.CadesT. CAdES-LT and CAdES-LTA also take the validation data into account: a chain that needs no revocation data (self-signed certificates) is CAdES-LT when its CadesSignatureInfo.Level is LT. CadesSignatureInfo.Level is the effective level.

public DateTime SignatureTime { get; }

Gets the signing time claimed by the signer (the time of the signer's computer, in UTC), or DateTime.MinValue when the signature has no signing time. For a time-stamped signature, the trusted time is TimestampInfo.SignatureTime of CadesSignatureInfo.TimestampInfo.

public TimestampInfo TimestampInfo { get; }

Gets the time-stamp of the signature, or null when the signature is not time-stamped.

public bool ValidationDataComplete { get; }

Gets a value indicating whether the signature contains the complete validation data: an OCSP response or a CRL for every certificate (except the root) of the chains of the signer and of the time-stamping authority of the signature time-stamp, valid at the time of the time-stamp.

CadesVerify class

Namespace: SignLib.Cades · Assembly: SignLib.dll

public class CadesVerify

Verifies a CMS / PKCS#7 or CAdES signature (attached or detached, binary or Base64 encoded) and gets the information about its signers.

Constructors
public CadesVerify(string signedFile, string librarySerialNumberLicense)

Initializes a new instance of the CadesVerify class and verifies a signed file.

signedFile
The path of the signed file (e.g. document.pdf.p7s).
librarySerialNumberLicense
The serial number provided to register the library.

Exceptions.

  • FileNotFoundException: The file does not exist.
  • CryptographicException: The file is not a CMS / PKCS#7 signature.
public CadesVerify(byte[] signedArray, string librarySerialNumberLicense)

Initializes a new instance of the CadesVerify class and verifies a signature.

signedArray
The signature, with the signed document.
librarySerialNumberLicense
The serial number provided to register the library.

Exceptions.

  • CryptographicException: The data is not a CMS / PKCS#7 signature.
public CadesVerify(byte[] detachedSignedArray, byte[] originalUnsignedFile, string librarySerialNumberLicense)

Initializes a new instance of the CadesVerify class and verifies a detached signature.

detachedSignedArray
The detached signature.
originalUnsignedFile
The signed document.
librarySerialNumberLicense
The serial number provided to register the library.

Exceptions.

  • CryptographicException: The data is not a CMS / PKCS#7 signature.
public CadesVerify(Stream signedFile, Stream documentOutput, string librarySerialNumberLicense)

Initializes a new instance of the CadesVerify class and verifies a signature read from a stream, without holding the signed document in memory: for large documents. The stream is read once: the document (the encapsulated content of an attached signature, e.g. a .p7m file) is only hashed and, when documentOutput is set, copied to it. CadesVerify.UnsignedDocument is then null.

signedFile
The signature (binary, DER or BER), from its current position. A Base64 encoded signature is read into memory.
documentOutput
The stream that receives the signed document, or null. It is not closed.
librarySerialNumberLicense
The serial number provided to register the library.

Exceptions.

  • CryptographicException: The data is not a CMS / PKCS#7 signature.
public CadesVerify(byte[] detachedSignedArray, Stream originalUnsignedFile, string librarySerialNumberLicense)

Initializes a new instance of the CadesVerify class and verifies a detached signature of a document read from a stream, without holding the document in memory: for large documents. The document is read once, to compute its digests.

detachedSignedArray
The detached signature.
originalUnsignedFile
The signed document, read from its current position to its end.
librarySerialNumberLicense
The serial number provided to register the library.

Exceptions.

  • CryptographicException: The data is not a CMS / PKCS#7 signature.
Properties
public string DocumentName { get; }

Gets the name of the signed document: the document name signed attribute, or the name of the signed file without its extension (e.g. document.pdf for document.pdf.p7s). It is null when it is not known.

public SignatureLevel Level { get; }

Gets the effective level of the signature (B, T, LT or LTA): the lowest level of its signers (the level of each signer is CadesSignatureInfo.Level).

public List<CadesSignatureInfo> Signatures { get; }

Gets the signers of the signature.

public CadesSignatureStandard SignatureStandard { get; }

Gets the format of the signature: the lowest format of its signers (the format of each signer is CadesSignatureInfo.SignatureStandard).

The format is detected from the attributes of the signers (a CAdES-BES signature with the signature time-stamp is CadesSignatureStandard.CadesT); CAdES-LT and CAdES-LTA also take their validation data into account. CadesVerify.Level is the effective level, computed from the validation data.

public byte[] UnsignedDocument { get; }

Gets the signed document, or null for a detached signature verified without the document.

CadesLtvLevel enum

Namespace: SignLib.Cades · Assembly: SignLib.dll

public enum CadesLtvLevel

The revocation data included in the long term CAdES signatures (CAdES-C, CAdES-X Long, CAdES-A, CAdES-LT and CAdES-LTA), for the certificate chains of the signer and of the time-stamping authority (the roots excepted).

MemberValueDescription
None0No revocation data (accepted only with AllowIncompleteValidationData).
IncludeCrl1The CRL of every certificate.
IncludeCrlAndOcsp2The CRL and the OCSP response of every certificate.
IncludeOcspOnly3The OCSP response of the signing (and time-stamping) certificate, its CRL only when the OCSP response is not available; the CRLs of the CA certificates, their OCSP responses only when the CRL is not available. A large CRL of the signing certificate is not downloaded when the OCSP responder answers.

CadesSignatureStandard enum

Namespace: SignLib.Cades · Assembly: SignLib.dll

public enum CadesSignatureStandard

The format of the signatures created by CadesSignature.

MemberValueDescription
Cms0CMS / PKCS#7 signature, recognized by the older software.
CadesBes1CAdES-BES signature (CAdES-BASELINE-B): the signing certificate is referenced by the ESS signing-certificate-v2 signed attribute (signing-certificate for SHA-1). No other ETSI attribute is added. When CadesSignature.TimeStamping has a server, the signature time-stamp is added too (the signature is then CadesSignatureStandard.CadesT).
CadesT7CAdES-T signature (CAdES-BASELINE-T, ETSI EN 319 122-1): a CAdES-BES signature with the signature time-stamp (the signature-time-stamp unsigned attribute), which proves that the signature existed at the time of the time-stamp. It contains no validation data (see CadesSignatureStandard.CadesLT). It requires a time-stamping server (CadesSignature.TimeStamping): without one, the signature is not created.
CadesC2CAdES-C signature: adds the complete certificate and revocation references, together with the certificate and revocation values. It is built on the signature time-stamp (CAdES-T): a time-stamping server is required.
CadesXL3CAdES-X Long signature: the CAdES-C attributes plus the time-stamp of the references (escTimeStamp). The time-stamps require a time-stamping server. Without one, the signature is not created.
CadesA4CAdES-A (long term archival) signature, as defined by ETSI TS 101 733: the certificate and revocation values (unsigned attributes) plus an archive time-stamp (v3, ETSI EN 319 122-1) of the signature and of its validation data. The time-stamps require a time-stamping server (TimeStamping.ServerUrl): without one, the signature is not created. The validators (e.g. DSS) report it as CAdES-A, not as CAdES-BASELINE-LTA; for the baseline profile, use CadesSignatureStandard.CadesLTA.
CadesLT5CAdES-BASELINE-LT signature (ETSI EN 319 122-1): a signature time-stamp, and the certificates and the revocation data (CRLs and OCSP responses) of the signing certificate and of the time-stamp, which are written in the certificates and crls fields of the CMS SignedData (not as unsigned attributes). The validators (e.g. the European Commission DSS) report it as CAdES-BASELINE-LT. It requires a time-stamping server (CadesSignature.TimeStamping).
CadesLTA6CAdES-BASELINE-LTA signature (ETSI EN 319 122-1): a signature time-stamp, the certificates and the revocation data (CRLs and OCSP responses) of the signing certificate and of the time-stamp, which are written in the certificates and crls fields of the CMS SignedData (not as unsigned attributes, as in CadesSignatureStandard.CadesA), and an archive time-stamp v3 of the signature and of all this validation data: CadesSignatureStandard.CadesLT plus the archive time-stamp. The validators (e.g. the European Commission DSS) report it as CAdES-BASELINE-LTA. It requires a time-stamping server (CadesSignature.TimeStamping), which is used for the signature time-stamp and for the archive time-stamp.

18.4 Namespace SignLib.Xml

TypeDescription
XadesProductionPlace classPlace where a XAdES signature was produced (xades:SignatureProductionPlaceV2, ETSI EN 319 132-1).
XadesSignature classSigns documents with XAdES signatures (the baseline levels B, T, LT and LTA of ETSI EN 319 132-1), enveloped in an XML document or detached from a file of any type, and verifies them.
XadesSignatureInfo classInformation about a XAdES (or XMLDSig) signature of an XML document or of an ASiC-E container (see XadesSignature.GetSignatures and AsicSignature.GetSignatures).
XmlSignature classSigns XML documents with enveloped XMLDSig signatures (RSA or ECDSA) and verifies them.
XmlSignatureVerificationPolicy static classThe policy of the verification of the XML signatures (XMLDSig, XAdES, ASiC-E, Office documents).
XadesCommitmentType enumCommitment type of a XAdES signature (xades:CommitmentTypeIndication, ETSI EN 319 132-1 and ETSI TS 119 172-1): what the signer declares by signing.
XadesLtvLevel enumThe revocation data included in the XAdES-LT and XAdES-LTA signatures.
XadesSignaturePackaging enumHow a XAdES signature is packaged with the signed data.
XadesSignatureStandard enumThe XAdES baseline levels (ETSI EN 319 132-1).
XmlSignatureType enumCanonicalization method used by the XmlSignature class.

XadesProductionPlace class

Namespace: SignLib.Xml · Assembly: SignLib.dll

public class XadesProductionPlace

Place where a XAdES signature was produced (xades:SignatureProductionPlaceV2, ETSI EN 319 132-1). All the fields are optional and the empty fields are not written. The country should be an ISO 3166 code (e.g. "RO").

Properties
public string City { get; set; }

Gets or sets the city.

public string CountryName { get; set; }

Gets or sets the country (an ISO 3166 code is recommended, e.g. "RO").

public string PostalCode { get; set; }

Gets or sets the postal code.

public string StateOrProvince { get; set; }

Gets or sets the state or province.

public string StreetAddress { get; set; }

Gets or sets the street address.

XadesSignature class

Namespace: SignLib.Xml · Assembly: SignLib.dll

public class XadesSignature

Signs documents with XAdES signatures (the baseline levels B, T, LT and LTA of ETSI EN 319 132-1), enveloped in an XML document or detached from a file of any type, and verifies them. A document can have several parallel signatures: a new signature does not invalidate the existing ones.

Constructors
public XadesSignature(string librarySerialNumberLicense)

Initializes a new instance of the XadesSignature class.

librarySerialNumberLicense
The serial number provided to register the library.
Properties
public bool AllowIncompleteValidationData { get; set; }

Gets or sets a value indicating whether a long term signature (XAdES-LT and XAdES-LTA, and the renewal of the archive time-stamps) is created even when its validation data is incomplete. The default value is false: a ValidationDataException is thrown (before the document is written) when the revocation data (OCSP response or CRL) of a certificate of the signer or of a time-stamping authority cannot be obtained (it lists the certificates and the reasons), and an InvalidOperationException when LtvLevel is None. When it is true, the signature is created with the data that could be obtained (the behaviour of the earlier versions).

public XadesCommitmentType CommitmentType { get; set; }

Gets or sets the commitment type declared by the signer (xades:CommitmentTypeIndication), e.g. ProofOfApproval or ProofOfOrigin. The default value is XadesCommitmentType.None: the commitment is a signed statement that only the signer can choose (it is optional in ETSI EN 319 132-1 and not required by eIDAS).

public X509Certificate2 DigitalSignatureCertificate { get; set; }

Gets or sets the signing certificate (see the DigitalCertificate class).

public HashAlgorithm HashAlgorithm { get; set; }

Gets or sets the hash algorithm of the signature: SHA256 (the default), SHA384 or SHA512. It is used for the signature method, the reference digests and the digest of the signing certificate. SHA1 is not supported for new signatures (NotSupportedException), but the existing SHA-1 signatures can be verified.

public XadesLtvLevel LtvLevel { get; set; }

Gets or sets the revocation data included in the XAdES-LT and XAdES-LTA signatures. The default value is XadesLtvLevel.IncludeOcspOnly.

public int MaxCrlSize { get; set; }

Gets or sets the maximum size, in bytes, of a CRL included in the XAdES-LT and XAdES-LTA signatures: larger CRLs are skipped. The default value is 1 MB.

public XadesSignaturePackaging SignaturePackaging { get; set; }

Gets or sets how the signature is packaged. XadesSignaturePackaging.Enveloped (the default): the signature is added to the signed XML document. XadesSignaturePackaging.Detached: the signature is a separate XML file that references the signed file; the signed file can be of any type (PDF, DOCX, ZIP...), it is not changed, and it is needed to verify the signature. Several signers of the same file create separate signature files.

public XadesProductionPlace SignatureProductionPlace { get; set; }

Gets or sets the place where the signature is created (xades:SignatureProductionPlaceV2). The default value is null: the property is not added.

public XadesSignatureStandard SignatureStandard { get; set; }

Gets or sets the XAdES baseline level of the signature (ETSI EN 319 132-1). The default value is XadesSignatureStandard.XadesB. XadesT, XadesLT and XadesLTA require TimeStamping.ServerUrl. As for the PDF signatures, a XadesB signature is also time-stamped (XAdES-T) when TimeStamping.ServerUrl is set.

public TimestampSettings TimeStamping { get; set; }

Gets or sets the time-stamping settings (required for the XAdES-T, XAdES-LT and XAdES-LTA signatures).

Methods
public void AddArchiveTimestamp(string inputFile, string outputFile)

Adds a new archive time-stamp to every XAdES-LTA signature of an XML document (re-time-stamping). Before the new xades141:ArchiveTimeStamp, the certificates and the current revocation data needed to validate the previous time-stamps are added (xades141:TimeStampValidationData). Call it periodically, before the certificate of the time-stamping authority of the last archive time-stamp expires (or its algorithms become weak), to keep the signatures verifiable in the long term. It requires TimeStamping.ServerUrl and uses LtvLevel and MaxCrlSize; the signing certificate is not needed. The other signatures are not changed.

inputFile
The path of the XML document with XAdES-LTA signatures.
outputFile
The path of the re-time-stamped document (it can be the input file).
public void AddArchiveTimestamp(string signatureFile, string outputFile, string originalFile)

Adds a new archive time-stamp to every XAdES-LTA signature of a detached signature file (re-time-stamping), as AddArchiveTimestamp(inputFile, outputFile) does for enveloped signatures. The original file is needed because it is part of the time-stamped data.

signatureFile
The path of the detached XAdES-LTA signature (XML).
outputFile
The path of the re-time-stamped signature file (it can be the signature file).
originalFile
The path of the signed file.

Exceptions.

  • FileNotFoundException: The original file does not exist.
  • ArgumentException: The output file is the original file.
public void ApplyDigitalSignature(string inputFile, string outputFile)

Signs a document. The output file is deleted when the signature fails (unless it is the input file).

inputFile
The path of the document to sign: an XML document (Enveloped) or any file (Detached).
outputFile
The path of the signed XML document (Enveloped) or of the signature file (Detached).

Exceptions.

  • FileNotFoundException: The input file does not exist.
  • ArgumentException: The time-stamping server is required, or the signature file of a detached signature is the signed file.
  • NotSupportedException: The hash algorithm is SHA1.
public void ExtendSignature(string inputFile, string outputFile, XadesSignatureStandard level)

Extends the XAdES signatures of an XML document to a higher level (B to T, LT or LTA; T to LT or LTA; LT to LTA): only the missing time-stamp, validation data and archive time-stamp are added; the signatures already at the level (or above it) are not changed. It requires TimeStamping.ServerUrl and uses LtvLevel, MaxCrlSize and AllowIncompleteValidationData; the signing certificate is not needed.

inputFile
The path of the XML document with XAdES signatures.
outputFile
The path of the extended document (it can be the input file).
level
The level: XadesSignatureStandard.XadesT, XadesSignatureStandard.XadesLT or XadesSignatureStandard.XadesLTA.

Exceptions.

  • CryptographicException: A signature is not valid or is not a XAdES signature.
public void ExtendSignature(string signatureFile, string outputFile, string originalFile, XadesSignatureStandard level)

Extends a detached XAdES signature file to a higher level, as ExtendSignature(inputFile, outputFile, level) does for enveloped signatures. The original file is needed to verify the signature and for the archive time-stamp.

signatureFile
The path of the detached XAdES signature (XML).
outputFile
The path of the extended signature file (it can be the signature file).
originalFile
The path of the signed file.
level
The level: XadesT, XadesLT or XadesLTA.
public X509Certificate2 GetDigitalSignatureCertificate(string inputFile)

Gets the signing certificate of the first signature of an XML document.

inputFile
The path of the document.

Returns. The signing certificate.

public X509Certificate2 GetDigitalSignatureCertificate(Stream inputFile)

Gets the signing certificate of the first signature of an XML document.

inputFile
The document.

Returns. The signing certificate.

public X509Certificate2 GetDigitalSignatureCertificate(string inputFile, int signatureIndex)

Gets the signing certificate of a signature of an XML document.

inputFile
The path of the document.
signatureIndex
The 0-based index of the signature, in document order.

Returns. The signing certificate.

public X509Certificate2 GetDigitalSignatureCertificate(Stream inputFile, int signatureIndex)

Gets the signing certificate of a signature of an XML document.

inputFile
The document.
signatureIndex
The 0-based index of the signature, in document order.

Returns. The signing certificate.

public int GetNumberOfSignatures(string inputFile)

Gets the number of signatures of an XML document.

inputFile
The path of the document.

Returns. The number of signatures.

public int GetNumberOfSignatures(Stream inputFile)

Gets the number of signatures of an XML document.

inputFile
The document.

Returns. The number of signatures.

public string GetSignatureAlgorithm(string inputFile)

Gets the signature algorithm of the first signature of an XML document (e.g. RSA-SHA256).

inputFile
The path of the document.

Returns. The signature algorithm.

public string GetSignatureAlgorithm(Stream inputFile)

Gets the signature algorithm of the first signature of an XML document (e.g. RSA-SHA256).

inputFile
The document.

Returns. The signature algorithm.

public List<XadesSignatureInfo> GetSignatures(string signatureFile)

Gets the information about the signatures of an XML document (enveloped signatures, or a detached signature whose references are in the same document): validity, certificate, time-stamp, effective level (B, T, LT, LTA) and completeness of the embedded validation data.

signatureFile
The path of the signed XML document.

Returns. The signatures, in document order.

public List<XadesSignatureInfo> GetSignatures(string signatureFile, string originalFile)

Gets the information about the signatures of a detached signature file (see XadesSignature.GetSignatures).

signatureFile
The path of the detached signature (XML).
originalFile
The path of the signed file.

Returns. The signatures, in document order.

Exceptions.

  • FileNotFoundException: The original file does not exist.
public void SetSignaturePolicyInformation(string policyIdentifier, byte[] policyHash, string policyDigestAlgorithm, string policyUrl)

Sets the explicit signature policy of the signatures (xades:SignaturePolicyIdentifier), when a regulation or a relying party requires one. By default there is no policy.

policyIdentifier
The identifier of the policy: an OID (e.g. 2.16.724.1.3.1.1.2.1.9, with or without the urn:oid: prefix) or a URI. Null removes the policy.
policyHash
The digest of the policy document.
policyDigestAlgorithm
The digest algorithm of policyHash: an OID (e.g. 2.16.840.1.101.3.4.2.1) or a name (SHA1, SHA256, SHA384, SHA512). SHA1 is accepted because many published policies are referenced by a SHA-1 digest.
policyUrl
The URL of the policy document (xades:SPURI), or null.
public bool VerifyDigitalSignature(string inputFile)

Verifies all the signatures of an XML document.

inputFile
The path of the document.

Returns. True if every signature is valid.

Exceptions.

  • CryptographicException: The document has no signature.
public bool VerifyDigitalSignature(Stream inputFile)

Verifies all the signatures of an XML document.

inputFile
The document.

Returns. True if every signature is valid.

Exceptions.

  • CryptographicException: The document has no signature.
public bool VerifyDigitalSignature(string inputFile, int signatureIndex)

Verifies a signature of an XML document.

inputFile
The path of the document.
signatureIndex
The 0-based index of the signature, in document order.

Returns. True if the signature is valid.

public bool VerifyDigitalSignature(Stream inputFile, int signatureIndex)

Verifies a signature of an XML document.

inputFile
The document.
signatureIndex
The 0-based index of the signature, in document order.

Returns. True if the signature is valid.

public bool VerifyDigitalSignature(string inputFile, X509Certificate2 certificate)

Verifies that an XML document has a valid signature created with a certificate.

inputFile
The path of the document.
certificate
The certificate of the expected signer.

Returns. True if a signature of the document is valid for the certificate.

public bool VerifyDigitalSignature(Stream inputFile, X509Certificate2 certificate)

Verifies that an XML document has a valid signature created with a certificate.

inputFile
The document.
certificate
The certificate of the expected signer.

Returns. True if a signature of the document is valid for the certificate.

public bool VerifyDigitalSignature(string signatureFile, string originalFile)

Verifies a detached signature: all the signatures of the signature file must be valid for the original file.

signatureFile
The path of the detached signature (XML).
originalFile
The path of the signed file (it can have been renamed).

Returns. True if every signature is valid.

Exceptions.

  • FileNotFoundException: The original file does not exist.
public bool VerifyDigitalSignature(string signatureFile, string originalFile, X509Certificate2 certificate)

Verifies that a detached signature file has a valid signature of the original file, created with a certificate.

signatureFile
The path of the detached signature (XML).
originalFile
The path of the signed file (it can have been renamed).
certificate
The certificate of the expected signer.

Returns. True if a signature is valid for the certificate.

Exceptions.

  • FileNotFoundException: The original file does not exist.

XadesSignatureInfo class

Namespace: SignLib.Xml · Assembly: SignLib.dll

public class XadesSignatureInfo

Information about a XAdES (or XMLDSig) signature of an XML document or of an ASiC-E container (see XadesSignature.GetSignatures and AsicSignature.GetSignatures).

Properties
public IReadOnlyList<TimestampInfo> ArchiveTimestamps { get; }

Gets the valid archive time-stamps of the signature (xades141:ArchiveTimeStamp): each token is valid, issued by a time-stamping certificate valid at its time, and covers the signature and the properties before it. Only these time-stamps make the signature LTA.

public int InvalidArchiveTimestampCount { get; }

Gets the number of the archive time-stamps that are not valid (altered, issued by a certificate that is not a valid time-stamping certificate, not covering the signature, or not verifiable, e.g. a detached signature verified without its original file).

public SignatureLevel Level { get; }

Gets the effective level of the signature (B, T, LT, LTA), determined from what it contains; None for a XMLDSig signature without XAdES properties or for a signature that is not valid.

public IReadOnlyList<MissingValidationData> MissingValidationData { get; }

Gets the certificates without validation data in the signature (empty when ValidationDataComplete is true).

public X509Certificate2 SignatureCertificate { get; }

Gets the signing certificate, or null when it is not in the signature.

public bool SignatureIsTimestamped { get; }

Gets a value indicating whether the signature has a signature time-stamp whose message imprint is the hash of the signature value.

public bool SignatureIsValid { get; }

Gets a value indicating whether the signature is valid (its references and its signature value).

public TimestampInfo TimestampInfo { get; }

Gets the signature time-stamp, or null.

public bool ValidationDataComplete { get; }

Gets a value indicating whether the signature contains the complete validation data: an OCSP response or a CRL for every certificate (except the root) of the chains of the signer and of the time-stamping authority of the signature time-stamp, valid at the time of the time-stamp.

XmlSignature class

Namespace: SignLib.Xml · Assembly: SignLib.dll

public class XmlSignature

Signs XML documents with enveloped XMLDSig signatures (RSA or ECDSA) and verifies them. A document can have several parallel signatures: a new signature does not invalidate the existing ones.

Constructors
public XmlSignature(string librarySerialNumberLicense)

Initializes a new instance of the XmlSignature class.

librarySerialNumberLicense
The serial number provided to register the library.
Properties
public X509Certificate2 DigitalSignatureCertificate { get; set; }

Gets or sets the signing certificate (see the DigitalCertificate class).

public HashAlgorithm HashAlgorithm { get; set; }

Gets or sets the hash algorithm of the signature: SHA256 (the default), SHA384 or SHA512. SHA1 is not supported for new signatures (NotSupportedException), but the existing SHA-1 signatures can be verified.

public bool IncludeKeyInfo { get; set; }

Gets or sets a value indicating whether the key of the signer is included in the signature: the RSA key value (modulus and exponent) or, for an ECDSA key, the signing certificate (SignedXml does not support the ECDSA key values). The default value is true.

public bool IncludeSignatureCertificate { get; set; }

Gets or sets a value indicating whether the signing certificate is included in the signature. The default value is true.

public bool PreserveWhitespace { get; set; }

Gets or sets a value indicating whether the white space of the documents is preserved when they are signed and verified: the signed document is saved as it is. When it is false, the insignificant white space is removed when a document is loaded, and the signed document is saved indented. The default value is true.

public XmlSignatureType SignatureType { get; set; }

Gets or sets the canonicalization of the signature. The default value is XmlSignatureType.Default (http://www.w3.org/TR/2001/REC-xml-c14n-20010315).

Methods
public void ApplyDigitalSignature(string inputFile, string outputFile)

Signs an XML document. The output file is deleted when the signature fails (unless it is the input file).

inputFile
The path of the XML document to sign.
outputFile
The path of the signed document (it can be the input file).

Exceptions.

  • FileNotFoundException: The input file does not exist.
public void ApplyDigitalSignature(Stream inputStream, Stream outputStream)

Signs an XML document.

inputStream
The XML document to sign.
outputStream
The stream where the signed document is written.
public X509Certificate2 GetDigitalSignatureCertificate(string inputFile)

Gets the signing certificate of the first signature of an XML document.

inputFile
The path of the document.

Returns. The signing certificate.

public X509Certificate2 GetDigitalSignatureCertificate(Stream inputFile)

Gets the signing certificate of the first signature of an XML document.

inputFile
The document.

Returns. The signing certificate.

public X509Certificate2 GetDigitalSignatureCertificate(string inputFile, int signatureIndex)

Gets the signing certificate of a signature of an XML document.

inputFile
The path of the document.
signatureIndex
The 0-based index of the signature, in document order.

Returns. The signing certificate.

public X509Certificate2 GetDigitalSignatureCertificate(Stream inputFile, int signatureIndex)

Gets the signing certificate of a signature of an XML document.

inputFile
The document.
signatureIndex
The 0-based index of the signature, in document order.

Returns. The signing certificate.

public int GetNumberOfSignatures(string inputFile)

Gets the number of signatures of an XML document.

inputFile
The path of the document.

Returns. The number of signatures.

public int GetNumberOfSignatures(Stream inputFile)

Gets the number of signatures of an XML document.

inputFile
The document.

Returns. The number of signatures.

public string GetSignatureAlgorithm(string inputFile)

Gets the signature algorithm of the first signature of an XML document (e.g. RSA-SHA256).

inputFile
The path of the document.

Returns. The signature algorithm.

public string GetSignatureAlgorithm(Stream inputFile)

Gets the signature algorithm of the first signature of an XML document (e.g. RSA-SHA256).

inputFile
The document.

Returns. The signature algorithm.

public bool VerifyDigitalSignature(string inputFile)

Verifies all the signatures of an XML document.

inputFile
The path of the document.

Returns. True if every signature is valid.

Exceptions.

  • CryptographicException: The document has no signature.
public bool VerifyDigitalSignature(Stream inputFile)

Verifies all the signatures of an XML document.

inputFile
The document.

Returns. True if every signature is valid.

Exceptions.

  • CryptographicException: The document has no signature.
public bool VerifyDigitalSignature(string inputFile, int signatureIndex)

Verifies a signature of an XML document.

inputFile
The path of the document.
signatureIndex
The 0-based index of the signature, in document order.

Returns. True if the signature is valid.

public bool VerifyDigitalSignature(Stream inputFile, int signatureIndex)

Verifies a signature of an XML document.

inputFile
The document.
signatureIndex
The 0-based index of the signature, in document order.

Returns. True if the signature is valid.

public bool VerifyDigitalSignature(string inputFile, X509Certificate2 certificate)

Verifies that an XML document has a valid signature created with a certificate.

inputFile
The path of the document.
certificate
The certificate of the expected signer.

Returns. True if a signature of the document is valid for the certificate.

public bool VerifyDigitalSignature(Stream inputFile, X509Certificate2 certificate)

Verifies that an XML document has a valid signature created with a certificate.

inputFile
The document.
certificate
The certificate of the expected signer.

Returns. True if a signature of the document is valid for the certificate.

XmlSignatureVerificationPolicy static class

Namespace: SignLib.Xml · Assembly: SignLib.dll

public static class XmlSignatureVerificationPolicy

The policy of the verification of the XML signatures (XMLDSig, XAdES, ASiC-E, Office documents).

Properties
public static bool RejectSha1 { get; set; }

Gets or sets a value indicating whether the signatures that use SHA-1 (an RSA, DSA, ECDSA or HMAC SHA-1 signature method, or a SHA-1 digest of a reference) are refused at verification: they are reported as invalid. The default value is false (the older signatures, e.g. of Office documents, are still verified). SHA-1 is never used for new signatures.

XadesCommitmentType enum

Namespace: SignLib.Xml · Assembly: SignLib.dll

public enum XadesCommitmentType

Commitment type of a XAdES signature (xades:CommitmentTypeIndication, ETSI EN 319 132-1 and ETSI TS 119 172-1): what the signer declares by signing. It is a signed property, so it is part of what the signer commits to.

MemberValueDescription
None0No commitment type is declared (the CommitmentTypeIndication property is not added).
ProofOfOrigin1The signer recognizes to have created, approved and sent the signed data.
ProofOfReceipt2The signer recognizes to have received the content of the signed data.
ProofOfDelivery3A trusted service provider indicates that the signed data has been delivered to a recipient.
ProofOfSender4The entity signing has sent the signed data (but not necessarily created it).
ProofOfApproval5The signer has approved the content of the signed data.
ProofOfCreation6The signer has created the signed data (but not necessarily approved nor sent it).

XadesLtvLevel enum

Namespace: SignLib.Xml · Assembly: SignLib.dll

public enum XadesLtvLevel

The revocation data included in the XAdES-LT and XAdES-LTA signatures.

MemberValueDescription
None0No revocation data (only the certificates).
IncludeCrl1The CRLs of the certificate chains, when they are available.
IncludeCrlAndOcsp2The CRLs and the OCSP responses of the certificate chains, when they are available.
IncludeOcspOnly3The OCSP responses of the certificate chains, when they are available. The CRL of an end-entity certificate is included only when its OCSP response is not available; the CRLs of the CA certificates are included.

XadesSignaturePackaging enum

Namespace: SignLib.Xml · Assembly: SignLib.dll

public enum XadesSignaturePackaging

How a XAdES signature is packaged with the signed data.

MemberValueDescription
Enveloped0The signature is added to the signed XML document (only XML documents can be signed).
Detached1The signature is a separate XML file that references the signed file (of any type); the signed file is not changed, and it is needed to verify the signature.

XadesSignatureStandard enum

Namespace: SignLib.Xml · Assembly: SignLib.dll

public enum XadesSignatureStandard

The XAdES baseline levels (ETSI EN 319 132-1).

MemberValueDescription
XadesB0XAdES-B-B: the signing time, the signing certificate and the format of the signed data.
XadesT1XAdES-B-T: XAdES-B-B with a signature time-stamp. Requires TimeStamping.ServerUrl.
XadesLT2XAdES-B-LT (long term validation): XAdES-B-T with the certificates and the revocation data (CRL, OCSP) of the signing certificate and of the time-stamping authority. Requires TimeStamping.ServerUrl.
XadesLTA3XAdES-B-LTA (long term archival): XAdES-B-LT with an archive time-stamp. Requires TimeStamping.ServerUrl.

XmlSignatureType enum

Namespace: SignLib.Xml · Assembly: SignLib.dll

public enum XmlSignatureType

Canonicalization method used by the XmlSignature class.

MemberValueDescription
Default0Canonical XML 1.0 without comments (http://www.w3.org/TR/2001/REC-xml-c14n-20010315).
DefaultWithComments1Canonical XML 1.0 with comments (http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments).
Exclusive2Exclusive XML canonicalization without comments (http://www.w3.org/2001/10/xml-exc-c14n#).
ExclusiveWithComments3Exclusive XML canonicalization with comments (http://www.w3.org/2001/10/xml-exc-c14n#WithComments).

18.5 Namespace SignLib.Office

TypeDescription
OfficeSignatureInfo classA signature of an Office document and the result of its verification.
OfficeSignatureLine classA visible signature of a Word document (docx): an Office signature line.
OfficeSignatureLineInfo classA signature line of a Word document.
OfficeSignatureLineAlignment enumThe horizontal alignment of a new signature line.
OfficeSignatureLinePlacement enumWhere the visible signature is placed in the document.

OfficeSignatureInfo class

Namespace: SignLib.Office · Assembly: SignLib.dll

public class OfficeSignatureInfo

A signature of an Office document and the result of its verification.

Properties
public X509Certificate2 Certificate { get; }

Gets the signing certificate, or null.

public string CommitmentType { get; }

Gets the commitment type (e.g. Approved this document), or null.

public bool HasTimestamp { get; }

Gets a value indicating whether the signature has a time-stamp (XAdES-T or higher).

public bool HasValidationData { get; }

Gets a value indicating whether the signature includes the certificates and the revocation data (XAdES-LT).

public int Index { get; }

Gets the 0-based index of the signature, in the order of the signature parts of the document.

public bool IsValid { get; }

Gets a value indicating whether the signature is valid (the document was not changed after it was signed).

public bool IsVisible { get; }

Gets a value indicating whether the signature is visible (it signs a signature line).

public SignatureLevel Level { get; }

Gets the effective level of the signature (B, T, LT; Office signatures have no archive time-stamp), determined from what it contains; None for a signature without XAdES properties or that is not valid.

public IReadOnlyList<MissingValidationData> MissingValidationData { get; }

Gets the certificates without validation data in the signature (empty when ValidationDataComplete is true).

public string SetupId { get; }

Gets the identifier of the signature line signed by this signature, or null for an invisible signature.

public string SignatureAlgorithm { get; }

Gets the signature algorithm (e.g. RSA-SHA256).

public string SignatureComments { get; }

Gets the purpose of the signature (the comments of the signer), or null.

public string SignerName { get; }

Gets the name of the signer (the common name of the signing certificate).

public string SignerRole { get; }

Gets the role (title) claimed by the signer, or null.

public DateTime? SigningTime { get; }

Gets the signing time claimed by the signer (UTC), or null.

public string Status { get; }

Gets the result of the verification: Success for a valid signature, ContentModified when the document was changed after it was signed, ReferenceNotFound when a signed part is missing, InvalidSignature otherwise. The trust of the signing certificate is not verified.

public DateTime? TimestampTime { get; }

Gets the time of the time-stamp (UTC), or null.

public bool ValidationDataComplete { get; }

Gets a value indicating whether the signature contains the complete validation data: an OCSP response or a CRL for every certificate (except the root) of the chains of the signer and of the time-stamping authority.

OfficeSignatureLine class

Namespace: SignLib.Office · Assembly: SignLib.dll

public class OfficeSignatureLine

A visible signature of a Word document (docx): an Office signature line. Word shows the signature line with the signature of the signer when the signature is valid, and marks it as invalid when the document is changed.

Constructors
public OfficeSignatureLine()

Initializes a new instance of the OfficeSignatureLine class.

Properties
public OfficeSignatureLineAlignment Alignment { get; set; }

Gets or sets the alignment of a new signature line.

public int Height { get; set; }

Gets or sets the height of a new signature line, in points (1/72 inch). Default: 96.

public OfficeSignatureLinePlacement Placement { get; set; }

Gets or sets where the visible signature is placed.

public string SetupId { get; set; }

Gets or sets the identifier of the existing signature line to sign (a GUID, e.g. from OfficeSignature.GetSignatureLines), or null for the first unsigned signature line.

public bool ShowSignDate { get; set; }

Gets or sets a value indicating whether the signing date is shown on the signature line.

public byte[] SignatureImage { get; set; }

Gets or sets the image of the handwritten signature drawn above the line (PNG, JPEG, BMP or GIF), or null.

public string SignatureText { get; set; }

Gets or sets the text written above the line (usually the name of the signer). When it is empty and there is no OfficeSignatureLine.SignatureImage, the name of the signing certificate is written.

public string SigningInstructions { get; set; }

Gets or sets the instructions shown to the signer of a new signature line (in Word).

public string SuggestedSigner { get; set; }

Gets or sets the name of the signer shown under the line of a new signature line (e.g. John Smith). When it is empty, the name of the signing certificate is shown.

public string SuggestedSignerEmail { get; set; }

Gets or sets the e-mail address of the signer of a new signature line.

public string SuggestedSignerTitle { get; set; }

Gets or sets the title of the signer shown under the name of a new signature line (e.g. Manager).

public int Width { get; set; }

Gets or sets the width of a new signature line, in points (1/72 inch). Default: 192.

OfficeSignatureLineInfo class

Namespace: SignLib.Office · Assembly: SignLib.dll

public class OfficeSignatureLineInfo

A signature line of a Word document.

Properties
public bool IsSigned { get; }

Gets a value indicating whether the signature line is already signed by a valid signature (a signature that is not valid, e.g. of a modified document, does not sign the line).

public string SetupId { get; }

Gets the identifier of the signature line (a GUID, e.g. {5B4C1E3A-...}).

public string SuggestedSigner { get; }

Gets the suggested signer (the name shown under the line).

public string SuggestedSignerEmail { get; }

Gets the e-mail address of the suggested signer.

public string SuggestedSignerTitle { get; }

Gets the title of the suggested signer.

Methods
public string ToString()

OfficeSignatureLineAlignment enum

Namespace: SignLib.Office · Assembly: SignLib.dll

public enum OfficeSignatureLineAlignment

The horizontal alignment of a new signature line.

MemberValueDescription
Left0
Center1
Right2

OfficeSignatureLinePlacement enum

Namespace: SignLib.Office · Assembly: SignLib.dll

public enum OfficeSignatureLinePlacement

Where the visible signature is placed in the document.

MemberValueDescription
UseExistingOrAddNew0The first unsigned signature line of the document (created in Word with Insert - Signature Line, or by OfficeSignature.AddSignatureLine) is signed; when the document has no unsigned signature line, a new one is added at the end of the document.
UseExisting1An unsigned signature line of the document is signed (the one with OfficeSignatureLine.SetupId, or the first one). The signature fails when the document has no unsigned signature line.
AddNew2A new signature line is added at the end of the document and signed. The document must not be signed yet: adding the signature line changes the document and would invalidate the existing signatures.

18.6 Namespace SignLib.Asic

TypeDescription
AsicSignature classCreates, co-signs, verifies and re-time-stamps ASiC-E containers with XAdES signatures (ETSI EN 319 162-1): a single ZIP file (.asice) with the signed files (any number, of any type) and their XAdES signatures.

AsicSignature class

Namespace: SignLib.Asic · Assembly: SignLib.dll

public class AsicSignature

Creates, co-signs, verifies and re-time-stamps ASiC-E containers with XAdES signatures (ETSI EN 319 162-1): a single ZIP file (.asice) with the signed files (any number, of any type) and their XAdES signatures. Every signature covers all the files of the container.

Constructors
public AsicSignature(string librarySerialNumberLicense)

Initializes a new instance of the AsicSignature class.

librarySerialNumberLicense
The serial number provided to register the library.
Properties
public bool AllowIncompleteValidationData { get; set; }

Gets or sets a value indicating whether a long term signature (XAdES-LT and XAdES-LTA signatures of the container, and the renewal of the archive time-stamps) is created even when its validation data is incomplete. The default value is false: a ValidationDataException is thrown (before the document is written) when the revocation data (OCSP response or CRL) of a certificate of the signer or of a time-stamping authority cannot be obtained (it lists the certificates and the reasons), and an InvalidOperationException when LtvLevel is None. When it is true, the signature is created with the data that could be obtained (the behaviour of the earlier versions).

public XadesCommitmentType CommitmentType { get; set; }

Gets or sets the commitment type declared by the signer (xades:CommitmentTypeIndication), e.g. ProofOfApproval or ProofOfOrigin. The default value is XadesCommitmentType.None: the commitment is a signed statement that only the signer can choose (it is optional in ETSI EN 319 132-1 and not required by eIDAS).

public X509Certificate2 DigitalSignatureCertificate { get; set; }

Gets or sets the signing certificate (see the DigitalCertificate class).

public HashAlgorithm HashAlgorithm { get; set; }

Gets or sets the hash algorithm of the signatures: SHA256 (the default), SHA384 or SHA512. It is used for the signature method, the reference digests and the digest of the signing certificate. SHA1 is not supported for new signatures (NotSupportedException), but the existing SHA-1 signatures can be verified.

public XadesLtvLevel LtvLevel { get; set; }

Gets or sets the revocation data included in the XAdES-LT and XAdES-LTA signatures. The default value is XadesLtvLevel.IncludeOcspOnly.

public int MaxCrlSize { get; set; }

Gets or sets the maximum size, in bytes, of a CRL included in the XAdES-LT and XAdES-LTA signatures: larger CRLs are skipped. The default value is 1 MB.

public XadesProductionPlace SignatureProductionPlace { get; set; }

Gets or sets the place where the signatures are created (xades:SignatureProductionPlaceV2). The default value is null: the property is not added.

public XadesSignatureStandard SignatureStandard { get; set; }

Gets or sets the XAdES baseline level of the signatures. The default value is XadesSignatureStandard.XadesB. XadesT, XadesLT and XadesLTA require TimeStamping.ServerUrl. A XadesB signature is also time-stamped when TimeStamping.ServerUrl is set.

public TimestampSettings TimeStamping { get; set; }

Gets or sets the time-stamping settings (required for the XAdES-T, XAdES-LT and XAdES-LTA signatures).

Methods
public byte[] AddArchiveTimestamp(byte[] container)

Adds a new archive time-stamp to every XAdES-LTA signature of an ASiC-E container (re-time-stamping).

container
The container.

Returns. The re-time-stamped container.

Exceptions.

  • ArgumentException: The time-stamping server is not set.
  • CryptographicException: A signature is not valid, or the container has no XAdES-LTA signature.
public void AddArchiveTimestamp(string inputContainer, string outputContainer)

Adds a new archive time-stamp to every XAdES-LTA signature of an ASiC-E container (re-time-stamping), with the validation data of the previous time-stamps (xades141:TimeStampValidationData). It requires TimeStamping.ServerUrl.

inputContainer
The path of the container.
outputContainer
The path of the re-time-stamped container (it can be the input container).

Exceptions.

  • FileNotFoundException: The input container does not exist.
public byte[] AddSignature(byte[] container)

Adds a new signature (co-signature) to an ASiC-E container.

container
The ASiC-E container.

Returns. The co-signed container.

Exceptions.

  • CryptographicException: The container has no files.
public void AddSignature(string inputContainer, string outputContainer)

Adds a new signature (co-signature) to an ASiC-E container. The new signature covers all the files of the container and it is written to a new signature file; the existing signatures are not changed.

inputContainer
The path of the ASiC-E container.
outputContainer
The path of the co-signed container (it can be the input container).

Exceptions.

  • FileNotFoundException: The input container does not exist.
public byte[] CreateContainer(IDictionary<string, byte[]> dataFiles)

Creates a signed ASiC-E container with files and one signature.

dataFiles
The files to sign: the name in the container (e.g. contract.pdf or annexes/annex1.pdf) and the content.

Returns. The ASiC-E container (.asice).

public void CreateContainer(string[] dataFiles, string outputContainer)

Creates a signed ASiC-E container with files (stored with their file names) and one signature. The output container is deleted when the signature fails.

dataFiles
The paths of the files to sign (of any type).
outputContainer
The path of the ASiC-E container (.asice) to create.

Exceptions.

  • FileNotFoundException: A file does not exist.
public byte[] ExtendSignature(byte[] container, XadesSignatureStandard level)

Extends the XAdES signatures of an ASiC-E container to a higher level (B to T, LT or LTA; T to LT or LTA; LT to LTA): only the missing time-stamp, validation data and archive time-stamp are added; the signatures already at the level (or above it) are not changed. It requires TimeStamping.ServerUrl and uses LtvLevel, MaxCrlSize and AllowIncompleteValidationData; the signing certificate is not needed.

container
The container.
level
The level: XadesT, XadesLT or XadesLTA.

Returns. The container with the extended signatures.

Exceptions.

  • CryptographicException: A signature is not valid.
public void ExtendSignature(string inputContainer, string outputContainer, XadesSignatureStandard level)

Extends the XAdES signatures of an ASiC-E container file to a higher level, as ExtendSignature(byte[], level).

inputContainer
The path of the container.
outputContainer
The path of the extended container (it can be the input container).
level
The level: XadesT, XadesLT or XadesLTA.
public byte[] ExtractDataFile(string container, string dataFileName)

Extracts a signed file from an ASiC-E container.

container
The path of the container.
dataFileName
The name of the file in the container.

Returns. The content of the file.

public byte[] ExtractDataFile(byte[] container, string dataFileName)

Extracts a signed file from an ASiC-E container.

container
The container.
dataFileName
The name of the file in the container.

Returns. The content of the file.

Exceptions.

  • FileNotFoundException: The container has no file with this name.
public string[] GetDataFileNames(string container)

Gets the names of the signed files of an ASiC-E container.

container
The path of the container.

Returns. The names of the files.

public string[] GetDataFileNames(byte[] container)

Gets the names of the signed files of an ASiC-E container.

container
The container.

Returns. The names of the files.

public X509Certificate2 GetDigitalSignatureCertificate(string container, int signatureIndex)

Gets the signing certificate of a signature of an ASiC-E container.

container
The path of the container.
signatureIndex
The 0-based index of the signature (the signature files in name order).

Returns. The signing certificate.

public X509Certificate2 GetDigitalSignatureCertificate(byte[] container, int signatureIndex)

Gets the signing certificate of a signature of an ASiC-E container.

container
The container.
signatureIndex
The 0-based index of the signature (the signature files in name order).

Returns. The signing certificate.

Exceptions.

  • CryptographicException: The container has no signature.
  • ArgumentOutOfRangeException: The index is not valid.
public int GetNumberOfSignatures(string container)

Gets the number of signatures of an ASiC-E container.

container
The path of the container.

Returns. The number of signatures.

public int GetNumberOfSignatures(byte[] container)

Gets the number of signatures of an ASiC-E container.

container
The container.

Returns. The number of signatures.

public List<XadesSignatureInfo> GetSignatures(byte[] container)

Gets the information about the XAdES signatures of an ASiC-E container: validity, certificate, time-stamp, effective level (B, T, LT, LTA) and completeness of the embedded validation data.

container
The ASiC-E container.

Returns. The signatures of all the signature files of the container.

public void SetSignaturePolicyInformation(string policyIdentifier, byte[] policyHash, string policyDigestAlgorithm, string policyUrl)

Sets the explicit signature policy of the signatures (xades:SignaturePolicyIdentifier), when a regulation or a relying party requires one. By default there is no policy.

policyIdentifier
The identifier of the policy: an OID (with or without the urn:oid: prefix) or a URI. Null removes the policy.
policyHash
The digest of the policy document.
policyDigestAlgorithm
The digest algorithm of policyHash: an OID or a name (SHA1, SHA256, SHA384, SHA512).
policyUrl
The URL of the policy document (xades:SPURI), or null.
public bool VerifyDigitalSignature(string container)

Verifies an ASiC-E container.

container
The path of the container.

Returns. True if the container has at least one signature, all its signatures are valid, and every signature covers all the files of the container (a file added to a signed container makes the verification fail).

public bool VerifyDigitalSignature(byte[] container)

Verifies an ASiC-E container.

container
The container.

Returns. True if the container has at least one signature, all its signatures are valid, and every signature covers all the files of the container (a file added to a signed container makes the verification fail).

public bool VerifyDigitalSignature(string container, X509Certificate2 certificate)

Verifies that an ASiC-E container has a valid signature of all its files, created with a certificate.

container
The path of the container.
certificate
The certificate of the expected signer.

Returns. True if a signature of the container is valid for the certificate.

public bool VerifyDigitalSignature(byte[] container, X509Certificate2 certificate)

Verifies that an ASiC-E container has a valid signature of all its files, created with a certificate.

container
The container.
certificate
The certificate of the expected signer.

Returns. True if a signature of the container is valid for the certificate.

18.7 Namespace SignLib.Certificates

TypeDescription
CertificateCache static classThe cache of the certificate data used when signing, shared by all the signature classes of the process, so that the documents signed one after another (or in parallel) with the same certificate do not repeat the same work: the certificate chains (of the signers and of the time-stamping authorities);the parsed certificates;the private keys: one key object per certificate and per thread, kept open (for a smart card or a token, the key on which the PIN was entered, so that the PIN is not asked for every document; see CertificateCache.KeepSmartCardKeys).
CertificateCacheStatistics classThe number of cache misses of the CertificateCache since the process started.
CertificateRevokedException classThe exception thrown when a signature is created with a revoked certificate: an OCSP response with the status "revoked" (including a suspended certificate, reason certificateHold), or a CRL that lists the certificate with a revocation date in the past.
CertificateValidationResult classThe result of the validation of a certificate by CertificateValidator.
CertificateValidationSettings classThe settings of the validation of a certificate by CertificateValidator: the trusted roots, the additional certificates and the revocation checks.
CertificateValidator static classValidates the trust of a certificate, separately from the verification of a signature: the certificate chain up to a trusted root, the validity period of the certificates at a time (e.g.
DigitalCertificate classLoads, verifies and uses the certificates for signing: certificates from PFX files, from the Windows certificate store or from smart cards, and external signature providers (HSM, PKCS#11 modules, remote signing services).
Extensions classExtensions of the certificates created by X509CertificateGenerator: key usages, enhanced key usages, CRL distribution points, Authority Information Access, certificate policies, QC statements and the path length constraint of the CA certificates.
IExternalSignature interfaceAn external signature provider (e.g.
IRevocationDataProvider interfaceA source of revocation data provided by the application (e.g.
MissingValidationData classA certificate whose revocation data (OCSP response or CRL) could not be obtained for a long term signature (PAdES-LT/LTA, CAdES-LT/LTA/C/XL/A, XAdES-LT/LTA).
QualifiedCertificateInfo classThe qualified certificate statements (qcStatements extension, ETSI EN 319 412-5) declared by a certificate.
QualifiedCertificateStatements classQCStatements extension of a certificate (ETSI EN 319 412-5).
RevocationCache static classThe cache of the revocation data (OCSP responses and CRLs) downloaded when long term signatures are created (PAdES-LT/LTA, CAdES-LT/LTA/C/XL/A, XAdES-LT/LTA, ASiC-E and Office): the signatures created one after another, or in parallel, by the same process reuse the data instead of downloading it for every document.
ValidationDataException classThe exception thrown when a long term signature (PAdES-LT/LTA, CAdES-LT/LTA/C/XL/A, XAdES-LT/LTA) is requested and the revocation data (OCSP response or CRL) of a certificate of the signer or of the time-stamping authority cannot be obtained.
X509CertificateGenerator classGenerates X.509 certificates (RSA or ECDSA keys): self-signed certificates, certificates issued by a root (CA) certificate, and certificates issued for a certificate signing request (CSR).
CertificateEnhancedKeyUsage enumEnhanced (extended) key usages of a certificate (the extended key usage extension, RFC 5280 4.2.1.12).
CertificateKeyUsage enumKey usages of a certificate (the key usage extension, RFC 5280 4.2.1.3).
CertificateStatus enumStatus of a certificate, returned by DigitalCertificate.VerifyDigitalCertificate.
CertificateTrustStatus enumThe result of the validation of a certificate by CertificateValidator.
DigitalCertificateSearchCriteria enumCriterion used to find a certificate in the Windows certificate store (e.g.
EllipticCurve enumElliptic curve of an ECDSA key pair (named curves, RFC 5480 and RFC 5639).
KeyAlgorithm enumAlgorithm of the key pair generated by X509CertificateGenerator.
KeySize enumSize of an RSA or DSA key pair, in bits.
QcSemanticsIdentifier enumSemantics identifier of the serialNumber or organizationIdentifier of the subject (ETSI EN 319 412-1).
QualifiedCertificateType enumType of a qualified certificate (QcType statement, ETSI EN 319 412-5).
RevocationCheckMode enumHow CertificateValidator checks the revocation status of the certificates of a chain.
RevocationDataSource enumThe source of the revocation status of a certificate, in CertificateValidationResult.RevocationSources.
SignatureAlgorithm enumAlgorithm of the certificate signature.
SubjectAlternativeNameType enumType of a Subject Alternative Name.
SubjectType enumAttribute types of the subject of a certificate (see X509CertificateGenerator.AddToSubject).
VerificationType enumType of the verification of a certificate (see DigitalCertificate.VerifyDigitalCertificate).

CertificateCache static class

Namespace: SignLib.Certificates · Assembly: SignLib.dll

public static class CertificateCache

The cache of the certificate data used when signing, shared by all the signature classes of the process, so that the documents signed one after another (or in parallel) with the same certificate do not repeat the same work: the certificate chains (of the signers and of the time-stamping authorities);the parsed certificates;the private keys: one key object per certificate and per thread, kept open (for a smart card or a token, the key on which the PIN was entered, so that the PIN is not asked for every document; see CertificateCache.KeepSmartCardKeys). A key that fails is discarded and opened again once;the certificates loaded from the same PFX file or data with the same password (DigitalCertificate.LoadCertificate), while they are not disposed. The entries expire after CertificateCache.MaxAge. The PIN of a smart card is never kept. The external signature providers and the certificates selected by the user are not cached.

Properties
public static bool Enabled { get; set; }

Gets or sets a value indicating whether the certificate data is cached. The default value is true. Setting it to false clears the cache.

public static bool KeepSmartCardKeys { get; set; }

Gets or sets a value indicating whether the private keys of the smart cards and tokens are kept open between signatures (on the same thread), so that their PIN is entered once. The default value is true. Cards that require the PIN for every signature (qualified signature cards, "PIN always") still ask for it.

public static TimeSpan MaxAge { get; set; }

Gets or sets the time an entry is kept (from its creation). The default value is 1 hour: a certificate chain changed in the certificate stores of Windows (e.g. a new intermediate certificate) is seen at most after this time, or at once after CertificateCache.Clear.

public static CertificateCacheStatistics Statistics { get; }

Gets the number of certificate chains built, of private keys opened and of PFX files loaded since the process started (cache misses), for diagnostics.

Methods
public static void Clear()

Removes all the entries; the private keys are disposed. The certificates loaded from PFX files are not disposed (the application may still use them). The certification authority certificates of the PFX files are removed too: load a PFX file again (DigitalCertificate.LoadCertificate) to use them.

CertificateCacheStatistics class

Namespace: SignLib.Certificates · Assembly: SignLib.dll

public sealed class CertificateCacheStatistics

The number of cache misses of the CertificateCache since the process started.

Properties
public long ChainBuilds { get; }

Gets the number of certificate chains built.

public long PfxLoads { get; }

Gets the number of PFX files (or data) loaded.

public long PrivateKeyOpens { get; }

Gets the number of private keys opened.

CertificateRevokedException class

Namespace: SignLib.Certificates · Assembly: SignLib.dll

public class CertificateRevokedException : CryptographicException, ISerializable

The exception thrown when a signature is created with a revoked certificate: an OCSP response with the status "revoked" (including a suspended certificate, reason certificateHold), or a CRL that lists the certificate with a revocation date in the past. It concerns the certificate chain of the signer or of the time-stamping authority. No signed document is produced. The status "unknown" of an OCSP response does not throw this exception (the CRL is used instead). AllowIncompleteValidationData does not apply: a revoked certificate is always reported.

Properties
public X509Certificate2 Certificate { get; }

Gets the revoked certificate.

public bool IsTimestampAuthority { get; }

Gets a value indicating whether the certificate belongs to the certificate chain of the time-stamping authority (false: the certificate chain of the signer).

public string RevocationReason { get; }

Gets the revocation reason (RFC 5280 CRLReason, e.g. keyCompromise or certificateHold), or "unspecified".

public DateTime RevocationTime { get; }

Gets the revocation time (UTC).

CertificateValidationResult class

Namespace: SignLib.Certificates · Assembly: SignLib.dll

public class CertificateValidationResult

The result of the validation of a certificate by CertificateValidator.

Properties
public IList<X509Certificate2> Chain { get; }

Gets the certificate chain: the certificate first, then its issuers, up to the root (or up to the last certificate found, when the chain is not complete).

public bool IsTrusted { get; }

Gets a value indicating whether the certificate is trusted (CertificateValidationResult.Status is Trusted).

public IList<string> Notes { get; }

Gets the information that does not change the result (e.g. the source of the revocation status of each certificate, or a revocation after the validation time).

public IList<string> Problems { get; }

Gets the problems found, in English (e.g. "The certificate 'CN=...' was revoked on ...").

public IReadOnlyDictionary<string, RevocationDataSource> RevocationSources { get; }

Gets the source of the revocation status of each checked certificate, by thumbprint (None when no status was found).

public CertificateTrustStatus Status { get; }

Gets the result of the validation: the most serious problem found, or CertificateTrustStatus.Trusted.

public DateTime ValidationTime { get; }

Gets the time at which the certificate was validated, in UTC.

CertificateValidationSettings class

Namespace: SignLib.Certificates · Assembly: SignLib.dll

public class CertificateValidationSettings

The settings of the validation of a certificate by CertificateValidator: the trusted roots, the additional certificates and the revocation checks.

Constructors
public CertificateValidationSettings()

Initializes a new instance of the CertificateValidationSettings class with the default values: the trusted roots of Windows, OCSP then CRL, online revocation checks.

Properties
public bool CheckRevocationOfCaCertificates { get; set; }

Gets or sets a value indicating whether the revocation status of the certification authority certificates of the chain is checked too (not only of the certificate). The trust anchor itself is never checked. The default value is true.

public IList<byte[]> Crls { get; }

Gets the CRLs known by the application (DER or PEM), used before the online checks.

public X509Certificate2Collection IntermediateCertificates { get; }

Gets the intermediate certification authority certificates that can be used to build the chain, when they are not in the certificate stores of Windows (e.g. the certificates included in a signature).

public IList<byte[]> OcspResponses { get; }

Gets the OCSP responses known by the application (e.g. the validation data of a PAdES-LT, CAdES-LT or XAdES-LT signature), encoded OCSPResponse or BasicOCSPResponse. They are used before the online checks.

public RevocationCheckMode RevocationCheck { get; set; }

Gets or sets how the revocation status is checked. The default value is RevocationCheckMode.OcspThenCrl.

public X509Certificate2Collection TrustedRoots { get; }

Gets the certificates trusted by the application (trust anchors): usually root certificates, but a certification authority certificate can also be trusted directly. A chain that contains one of them is trusted from it.

public bool UseOnlineRevocation { get; set; }

Gets or sets a value indicating whether OCSP responses and CRLs are downloaded (from the URLs of the certificates). The default value is true. Set it to false to use only CertificateValidationSettings.OcspResponses and CertificateValidationSettings.Crls (e.g. the validation data embedded in a long term signature).

public bool UseWindowsTrustedRoots { get; set; }

Gets or sets a value indicating whether the trusted root certification authorities of Windows are trusted. The default value is true. Set it to false to trust only CertificateValidationSettings.TrustedRoots (the same result on every computer, whatever certificates are installed on it).

CertificateValidator static class

Namespace: SignLib.Certificates · Assembly: SignLib.dll

public static class CertificateValidator

Validates the trust of a certificate, separately from the verification of a signature: the certificate chain up to a trusted root, the validity period of the certificates at a time (e.g. the time of the time-stamp of a signature), their revocation status (OCSP, CRL) at that time, and the key usage of the certificate. The verification of the signatures (e.g. SignatureIsValid) checks only that the signed data was not changed and that the signature was made with the key of its certificate; it does not tell whether the certificate can be trusted. This class answers that question, only when the application asks for it. The result is technical: it does not tell whether a signature is a qualified electronic signature (the EU Trusted Lists are not used).

Methods
public static CertificateValidationResult Validate(X509Certificate2 certificate)

Validates a certificate now, with the default settings (the trusted roots of Windows, OCSP then CRL).

certificate
The certificate.

Returns. The result of the validation.

public static CertificateValidationResult Validate(X509Certificate2 certificate, CertificateValidationSettings settings)

Validates a certificate now.

certificate
The certificate.
settings
The settings, or null for the default settings.

Returns. The result of the validation.

public static CertificateValidationResult Validate(PdfSignatureInfo signature, CertificateValidationSettings settings)

Validates the certificate of a signature at the time of its time-stamp or, when it has none, now.

signature
A signature of a PDF document (PdfSignatureInfo).
settings
The settings, or null for the default settings.

Returns. The result of the validation.

Exceptions.

  • ArgumentException: The signature has no certificate (e.g. a document time-stamp).
public static CertificateValidationResult Validate(XadesSignatureInfo signature, CertificateValidationSettings settings)

Validates the certificate of a XAdES signature (XAdES, ASiC-E) at the time of its time-stamp or, when it has none, now. The validation data embedded in the signature (KeyInfo, CertificateValues, RevocationValues, TimeStampValidationData) is used, before the online sources.

signature
A XAdES signature (XadesSignatureInfo).
settings
The settings, or null for the default settings.

Returns. The result of the validation.

Exceptions.

  • ArgumentException: The signature has no certificate.
public static CertificateValidationResult Validate(CadesSignatureInfo signature, CertificateValidationSettings settings)

Validates the certificate of a CMS / CAdES signature at the time of its time-stamp or, when it has none, now.

signature
A signer of a CMS / CAdES signature (CadesSignatureInfo).
settings
The settings, or null for the default settings.

Returns. The result of the validation.

Exceptions.

  • ArgumentException: The signature has no certificate.
public static CertificateValidationResult Validate(X509Certificate2 certificate, DateTime validationTime, CertificateValidationSettings settings)

Validates a certificate at a time.

certificate
The certificate.
validationTime
The time at which the certificate must be valid: for a signature, the time of its time-stamp (a certificate that expired or was revoked after it does not affect the signature) or, without a time-stamp, the current time. A time of kind Unspecified is taken as UTC.
settings
The settings, or null for the default settings.

Returns. The result of the validation.

Exceptions.

  • ArgumentNullException: The certificate is null.

DigitalCertificate class

Namespace: SignLib.Certificates · Assembly: SignLib.dll

public class DigitalCertificate

Loads, verifies and uses the certificates for signing: certificates from PFX files, from the Windows certificate store or from smart cards, and external signature providers (HSM, PKCS#11 modules, remote signing services).

Fields
public static int Timeout

The timeout, in milliseconds, of the download of a CRL, of an OCSP response and of the other downloads of the library (e.g. a PDF document loaded from a URL). The default value is 20000 (20 seconds).

Properties
public static string SmartCardPin { get; set; }

Gets or sets the PIN of the signing certificate stored on a smart card. Some smart cards do not support this feature. The value is thread-local: it must be set on the thread that creates the signature.

public static IExternalSignature UseExternalSignatureProvider { set; }

Sets an external signature provider (e.g. a PKCS#11 module or an HSM) for the next signature created on the same thread by PdfSignature, CadesSignature, XmlSignature, XadesSignature or AsicSignature. The signing certificate (DigitalSignatureCertificate) needs no private key. The provider is thread-local and it is released at the end of the signing operation (also when the operation fails).

Methods
public static DateTime GetCertificateRevocationDate(X509Certificate2 certificate)

Gets the revocation date of a revoked certificate, from its CRL.

certificate
The revoked certificate.

Returns. The revocation date, in local time.

Exceptions.

  • CryptographicException: The certificate has no CRL, or it is not in its CRL.
public static List<CertificateKeyUsage> GetKeyUsage(X509Certificate2 certificate)

Gets the key usages of a certificate.

certificate
The certificate.

Returns. The key usages, or null when the certificate has no key usage extension.

public static QualifiedCertificateInfo GetQualifiedCertificateInfo(X509Certificate2 certificate)

Gets the qualified certificate statements declared by a certificate (ETSI EN 319 412-5): QcCompliance, QcSSCD (key on a qualified device), the types (signature, seal, website) and the legislations. They are declarations of the issuer: the qualified status is given by the EU Trusted Lists.

certificate
The certificate.

Returns. The statements, or null when the certificate has no (readable) qcStatements extension.

public static bool IsQualifiedCertificate(X509Certificate2 certificate)

Gets a value indicating whether a certificate declares itself as an EU qualified certificate: its qcStatements extension (1.3.6.1.5.5.7.1.3, ETSI EN 319 412-5) has the QcCompliance statement. A qcStatements extension without it (e.g. only the PSD2 or retention statements) is not a qualified certificate. The qualified status itself is given by the EU Trusted Lists. See DigitalCertificate.GetQualifiedCertificateInfo for the details.

certificate
The certificate.

Returns. True if the certificate declares QcCompliance.

public static X509Certificate2 LoadCertificate()

Loads a certificate from the certificate store of the current user. When more certificates match, the user selects one.

Returns. The certificate, or null when no certificate is selected.

public static X509Certificate2 LoadCertificate(string certificateSubject)

Loads a certificate from the certificate store of the current user, by subject name. When more certificates match, the user selects one.

certificateSubject
The subject name of the certificate. Use "" for all the certificates.

Returns. The certificate, or null when no certificate is selected.

public static X509Certificate2 LoadCertificate(byte[] certificate, string password)

Loads a certificate from the content of a PFX (PKCS#12) file. Dispose the certificate when it is not needed anymore: on .NET Framework, its private key is then deleted from the temporary key container.

The certificates of certification authorities that the PFX file contains (the intermediate and root certificates exported with the certificate) complete the certificate chain of the signatures created with this certificate: the certificates included in the signatures and the issuers of the OCSP and CRL requests. They are kept in memory (see CertificateCache.Clear), they are not installed in the certificate stores and they do not make the certificate trusted.

certificate
The content of the PFX file.
password
The password of the PFX file.

Returns. The certificate, with its private key.

Exceptions.

  • CryptographicException: The certificate cannot be loaded.
public static X509Certificate2 LoadCertificate(string certificateFile, string password)

Loads a certificate from a PFX (PKCS#12) file.

The certificates of certification authorities that the PFX file contains complete the certificate chain of the signatures created with this certificate (see DigitalCertificate.LoadCertificate).

certificateFile
The path of the PFX file.
password
The password of the PFX file.

Returns. The certificate, with its private key.

Exceptions.

  • CryptographicException: The certificate cannot be loaded.
  • FileNotFoundException: The file does not exist.
public static X509Certificate2 LoadCertificate(bool validOnly, DigitalCertificateSearchCriteria selectionType, string searchString)

Gets, without user intervention, the first certificate of the certificate store of the current user that matches a criterion.

validOnly
True to use only valid certificates.
selectionType
The criterion (a field of the subject, the thumbprint or the serial number).
searchString
The value searched for.

Returns. The certificate, or null when no certificate matches.

public static X509Certificate2 LoadCertificate(bool validOnly, string issuerName, string windowTitle, string windowDescription)

Loads a certificate from the certificate store of the current user, by issuer name. When more certificates match, the user selects one.

validOnly
True to use only valid certificates.
issuerName
The issuer name. Use "" for any issuer.
windowTitle
The title of the certificate selection window.
windowDescription
The description of the certificate selection window.

Returns. The certificate, or null when no certificate is selected.

public static X509Certificate2 LoadCertificate(bool validOnly, DigitalCertificateSearchCriteria selectionType, string searchString, bool fromLocalMachine)

Gets, without user intervention, the first certificate of the Windows certificate store that matches a criterion.

validOnly
True to use only valid certificates.
selectionType
The criterion (a field of the subject, the thumbprint or the serial number).
searchString
The value searched for.
fromLocalMachine
True to use the certificates of the local machine instead of the current user.

Returns. The certificate, or null when no certificate matches.

public static X509Certificate2 LoadCertificate(bool validOnly, DigitalCertificateSearchCriteria selectionType, string searchString, string smartCardPin)

Gets, without user intervention, the first certificate of the certificate store of the current user that matches a criterion.

validOnly
True to use only valid certificates.
selectionType
The criterion (a field of the subject, the thumbprint or the serial number).
searchString
The value searched for.
smartCardPin
The PIN of the smart card, or null. When it is set, the PIN window does not appear.

Returns. The certificate, or null when no certificate matches.

public static X509Certificate2 LoadCertificate(string certificateSubject, string windowTitle, string windowDescription, bool fromLocalMachine, string smartCardPin)

Loads a certificate from the Windows certificate store, by subject name. When more certificates match, the user selects one.

certificateSubject
The subject name of the certificate. Use "" for all the certificates.
windowTitle
The title of the certificate selection window.
windowDescription
The description of the certificate selection window.
fromLocalMachine
True to use the certificates of the local machine instead of the current user.
smartCardPin
The PIN of the smart card, or null. When it is set, the PIN window does not appear.

Returns. The certificate, or null when no certificate is selected.

public static X509Certificate2 LoadCertificate(bool validOnly, string issuerName, string windowTitle, string windowDescription, bool fromLocalMachine)

Loads a certificate from the Windows certificate store, by issuer name. When more certificates match, the user selects one.

validOnly
True to use only valid certificates.
issuerName
The issuer name. Use "" for any issuer.
windowTitle
The title of the certificate selection window.
windowDescription
The description of the certificate selection window.
fromLocalMachine
True to use the certificates of the local machine instead of the current user.

Returns. The certificate, or null when no certificate is selected.

public static X509Certificate2 LoadCertificate(bool validOnly, string issuerName, string windowTitle, string windowDescription, string smartCardPin)

Loads a certificate from the certificate store of the current user, by issuer name. When more certificates match, the user selects one.

validOnly
True to use only valid certificates.
issuerName
The issuer name. Use "" for any issuer.
windowTitle
The title of the certificate selection window.
windowDescription
The description of the certificate selection window.
smartCardPin
The PIN of the smart card, or null. When it is set, the PIN window does not appear.

Returns. The certificate, or null when no certificate is selected.

public static X509Certificate2 LoadCertificate(bool validOnly, DigitalCertificateSearchCriteria selectionType, string searchString, bool fromLocalMachine, string smartCardPin)

Gets, without user intervention, the first certificate of the Windows certificate store that matches a criterion.

validOnly
True to use only valid certificates.
selectionType
The criterion (a field of the subject, the thumbprint or the serial number).
searchString
The value searched for.
fromLocalMachine
True to use the certificates of the local machine instead of the current user.
smartCardPin
The PIN of the smart card, or null. When it is set, the PIN window does not appear.

Returns. The certificate, or null when no certificate matches.

public static X509Certificate2 LoadCertificate(bool validOnly, string issuerName, string windowTitle, string windowDescription, bool fromLocalMachine, string smartCardPin)

Loads a certificate from the Windows certificate store, by issuer name. When more certificates match, the user selects one.

validOnly
True to use only valid certificates.
issuerName
The issuer name. Use "" for any issuer.
windowTitle
The title of the certificate selection window.
windowDescription
The description of the certificate selection window.
fromLocalMachine
True to use the certificates of the local machine instead of the current user.
smartCardPin
The PIN of the smart card, or null. When it is set, the PIN window does not appear.

Returns. The certificate, or null when no certificate is selected.

public static CertificateStatus VerifyDigitalCertificate(X509Certificate2 certificate, VerificationType verificationType)

Verifies a certificate: its validity period (all the verification types) and, for OCSP, CRL and LDAP, its revocation status. CertificateStatus.Valid means that the certificate is in its validity period and not revoked; the certificate chain and the trust (a trusted root) are not verified: use CertificateValidator for a complete validation.

certificate
The certificate.
verificationType
The type of the verification.

Returns. The status of the certificate: CertificateStatus.Expired outside its validity period, otherwise the revocation status.

Exceptions.

  • CryptographicException: The certificate cannot be verified (the cause is the inner exception).

Extensions class

Namespace: SignLib.Certificates · Assembly: SignLib.dll

public class Extensions

Extensions of the certificates created by X509CertificateGenerator: key usages, enhanced key usages, CRL distribution points, Authority Information Access, certificate policies, QC statements and the path length constraint of the CA certificates.

Constructors
public Extensions()

Initializes a new instance of the Extensions class, without extensions.

Properties
public bool EnhancedKeyUsageIsCritical { get; set; }

Gets or sets a value indicating whether the enhanced key usage extension is critical. The default value is false.

public bool KeyUsageIsCritical { get; set; }

Gets or sets a value indicating whether the key usage extension is critical. The default value is false. The key usage extension of a CA certificate is always critical.

public int PathLengthConstraint { get; set; }

Gets or sets the path length constraint of the Basic Constraints extension of a CA certificate (generated with isRootCertificate = true): the maximum number of intermediate CA certificates that may follow it in a certification path (0 = only end-entity certificates may be issued). The default value is -1 (no constraint). When a CA certificate is issued by a loaded root certificate, the value must be smaller than the path length constraint of the root certificate.

public QualifiedCertificateStatements QcStatements { get; set; }

Gets or sets the QCStatements extension (ETSI EN 319 412-5) of the certificate. Nothing is added by default.

Methods
public void AddCaIssuersUrl(string caIssuersUrl)

Adds the URL of the issuer certificate (CA Issuers, e.g. http://www.example.com/ca.cer) to the Authority Information Access extension of the certificate.

caIssuersUrl
The absolute URL of the issuer certificate.

Exceptions.

  • ArgumentException: The value is not an absolute URL.
public void AddCertificatePolicy(string policyOid)

Adds a certificate policy (e.g. 0.4.0.194112.1.2 for QCP-n-qscd) to the Certificate Policies extension.

policyOid
The OID of the policy.

Exceptions.

  • ArgumentException: The OID is not valid.
public void AddCertificatePolicy(string policyOid, string cpsUrl, string userNotice)

Adds a certificate policy, with optional policy qualifiers, to the Certificate Policies extension.

policyOid
The OID of the policy.
cpsUrl
The URL of the Certification Practice Statement (CPS qualifier), or null.
userNotice
The explicit text of a User Notice qualifier (at most 200 characters), or null.

Exceptions.

  • ArgumentException: The OID, the URL or the text of the user notice is not valid.
public void AddCrlDistributionPoint(string crlUrl)

Adds a CRL distribution point (the URL of the CRL, e.g. http://crl.example.com/ca.crl) to the certificate.

crlUrl
The absolute URL of the CRL.

Exceptions.

  • ArgumentException: The value is not an absolute URL.
public void AddEnhancedKeyUsage(CertificateEnhancedKeyUsage enhancedKeyUsage)

Adds an enhanced (extended) key usage to the certificate.

enhancedKeyUsage
The enhanced key usage.

Exceptions.

  • ArgumentException: The value is not a known enhanced key usage.
public void AddEnhancedKeyUsage(Oid extensionOID)

Adds an enhanced (extended) key usage, given by its OID, to the certificate (e.g. 1.3.6.1.4.1.311.10.3.12).

extensionOID
The OID of the enhanced key usage.
public void AddKeyUsage(CertificateKeyUsage keyUsage)

Adds a key usage to the certificate.

keyUsage
The key usage.
public void AddOcspUrl(string ocspUrl)

Adds the URL of an OCSP responder to the Authority Information Access extension of the certificate.

ocspUrl
The absolute URL of the OCSP responder.

Exceptions.

  • ArgumentException: The value is not an absolute URL.

IExternalSignature interface

Namespace: SignLib.Certificates · Assembly: SignLib.dll

public interface IExternalSignature

An external signature provider (e.g. a PKCS#11 module, an HSM or a remote signing service), set with DigitalCertificate.UseExternalSignatureProvider.

Methods
public byte[] ApplySignature(byte[] message, Oid hashAlgorithm)

Signs a message: hashes it with the hash algorithm, then signs the hash with the private key of the signing certificate.

message
The data to sign: the DER encoded CMS signed attributes (PDF and CAdES signatures) or the canonicalized ds:SignedInfo (XML signatures: XMLDSig, XAdES, ASiC-E).
hashAlgorithm
The OID of the hash algorithm (e.g. 2.16.840.1.101.3.4.2.1 for SHA-256).

Returns. The signature value: PKCS#1 v1.5 for RSA; for ECDSA either the raw value r || s (as most PKCS#11 modules return it) or the DER SEQUENCE { r, s }. SignLib converts it to the form required by the signature format.

IRevocationDataProvider interface

Namespace: SignLib.Certificates · Assembly: SignLib.dll

public interface IRevocationDataProvider

A source of revocation data provided by the application (e.g. an internal mirror, a database, a server without Internet access), used when long term signatures are created. Set it with RevocationCache.Provider: it is asked before the OCSP responders and the CRL distribution points of the certificates. The data it returns is validated exactly as the downloaded data (signature of the responder or of the CRL issuer, validity, certificate) and is cached. Return null when the data is not available: the network is used then, unless RevocationCache.UseNetwork is false.

Methods
public byte[] GetCrl(X509Certificate2 certificate, string url)

Gets a CRL of a distribution point of a certificate.

certificate
The certificate.
url
The URL of the CRL distribution point of the certificate.

Returns. The CRL (DER or PEM), or null.

public byte[] GetOcspResponse(X509Certificate2 certificate, X509Certificate2 issuer)

Gets an OCSP response about a certificate.

certificate
The certificate.
issuer
The certificate of its issuer.

Returns. The DER encoded OCSPResponse or BasicOCSPResponse, or null.

MissingValidationData class

Namespace: SignLib.Certificates · Assembly: SignLib.dll

public sealed class MissingValidationData

A certificate whose revocation data (OCSP response or CRL) could not be obtained for a long term signature (PAdES-LT/LTA, CAdES-LT/LTA/C/XL/A, XAdES-LT/LTA).

Properties
public bool IsTimestampAuthority { get; }

Gets a value indicating whether the certificate belongs to the certificate chain of the time-stamping authority (false: the certificate chain of the signer).

public string Reason { get; }

Gets the reason why the revocation data is missing.

public string Subject { get; }

Gets the subject of the certificate.

public string Thumbprint { get; }

Gets the thumbprint (SHA-1 hash, hexadecimal) of the certificate.

Methods
public string ToString()

Returns the subject and the reason.

QualifiedCertificateInfo class

Namespace: SignLib.Certificates · Assembly: SignLib.dll

public sealed class QualifiedCertificateInfo

The qualified certificate statements (qcStatements extension, ETSI EN 319 412-5) declared by a certificate. They are declarations of the issuer: the qualified status of a certificate is given by the EU Trusted Lists.

Properties
public bool IsKeyOnQualifiedDevice { get; }

Gets a value indicating whether the certificate declares that its private key is in a qualified signature or seal creation device (QcSSCD, 0.4.0.1862.1.4).

public bool IsQcCompliant { get; }

Gets a value indicating whether the certificate declares that it is an EU qualified certificate (QcCompliance, 0.4.0.1862.1.1).

public List<string> Legislations { get; }

Gets the countries (ISO 3166 codes) under whose legislation the certificate is qualified (QcCCLegislation, 0.4.0.1862.1.7), for the certificates qualified outside the EU. Empty when not declared.

public int? RetentionPeriodYears { get; }

Gets the retention period, in years, of the information about the certificate (QcRetentionPeriod, 0.4.0.1862.1.3), or null when not declared.

public List<QualifiedCertificateType> Types { get; }

Gets the declared types of the certificate (QcType, 0.4.0.1862.1.6): electronic signature, electronic seal or website authentication. Empty when not declared (an EU qualified certificate without QcType is for electronic signatures).

QualifiedCertificateStatements class

Namespace: SignLib.Certificates · Assembly: SignLib.dll

public class QualifiedCertificateStatements

QCStatements extension of a certificate (ETSI EN 319 412-5). The statements declare the certificate as an EU qualified certificate; a certificate is recognized as qualified only when its issuer is a qualified trust service on an EU Trusted List. Nothing is added by default.

Properties
public bool QcCompliance { get; set; }

Gets or sets a value indicating whether the certificate is an EU qualified certificate (QcCompliance statement). The default value is false.

public bool QcSscd { get; set; }

Gets or sets a value indicating whether the private key resides in a qualified signature or seal creation device (QcSSCD statement). The default value is false.

public QualifiedCertificateType QcType { get; set; }

Gets or sets the type of the qualified certificate (QcType statement). The default value is QualifiedCertificateType.None.

public int RetentionPeriod { get; set; }

Gets or sets the number of years the registration information is kept after the certificate expires (QcRetentionPeriod statement). The default value is 0 (not added).

public QcSemanticsIdentifier SemanticsIdentifier { get; set; }

Gets or sets the semantics identifier of the subject identifier (id-qcs-pkixQCSyntax-v2 statement). The default value is QcSemanticsIdentifier.None.

Methods
public void AddPdsLocation(string url, string language)

Adds the location of a PKI Disclosure Statement (QcPDS statement).

url
The https URL of the PDS.
language
The language of the PDS, as an ISO 639-1 code (e.g. en).

Exceptions.

  • ArgumentException: The URL or the language is not valid.

RevocationCache static class

Namespace: SignLib.Certificates · Assembly: SignLib.dll

public static class RevocationCache

The cache of the revocation data (OCSP responses and CRLs) downloaded when long term signatures are created (PAdES-LT/LTA, CAdES-LT/LTA/C/XL/A, XAdES-LT/LTA, ASiC-E and Office): the signatures created one after another, or in parallel, by the same process reuse the data instead of downloading it for every document. It is shared by all the signature classes, it is kept in memory only and it is used only when signing (the verification of signatures and certificates always gets current data). An OCSP response is reused at most RevocationCache.OcspMaxAge after it was downloaded (5 minutes by default), and only while it is valid for at least one more minute (its nextUpdate). A response valid for less than one minute is not reused.A CRL is reused at most RevocationCache.CrlMaxAge after it was downloaded (1 hour by default), and only while it is valid for at least one more minute (its nextUpdate). The CRLs take at most RevocationCache.MaxCrlCacheSize bytes (the least recently used ones are removed).A failed download (unavailable server, invalid response) is remembered for RevocationCache.FailureRetention (60 seconds by default), so that the next documents do not wait again for the timeout of the same server.The signatures created in parallel for the same certificate download its data once.PAdES, CAdES, XAdES, ASiC-E and Office long term signatures: the OCSP responses embedded in the signature (chain of the signer and chain of the time-stamping authority) must be issued after the time-stamp (validators such as eParaksts reject an older one; the DSS default when signatures are augmented). A cached response issued earlier is not used: a new one is requested after each time-stamp. The cached (or added, or provided) response is used only when no newer one can be obtained.

Properties
public static TimeSpan CrlMaxAge { get; set; }

Gets or sets the maximum time a CRL is reused after it was downloaded. The default value is 1 hour. A CRL is never reused when it is valid for less than one more minute.

public static bool Enabled { get; set; }

Gets or sets a value indicating whether the revocation data is cached. The default value is true. Setting it to false clears the cache.

public static TimeSpan FailureRetention { get; set; }

Gets or sets the time a failed download (unavailable server, invalid response) is remembered: during this time the same OCSP responder or CRL is not requested again. The default value is 60 seconds. TimeSpan.Zero retries for every signature.

public static long MaxCrlCacheSize { get; set; }

Gets or sets the maximum total size, in bytes, of the cached CRLs: the least recently used CRLs are removed when it is exceeded. The default value is 100 MB.

public static TimeSpan OcspMaxAge { get; set; }

Gets or sets the maximum time an OCSP response is reused after it was downloaded. The default value is 5 minutes. A response is never reused when it is valid for less than one more minute. TimeSpan.Zero downloads a new response for every signature.

public static IRevocationDataProvider Provider { get; set; }

Gets or sets a source of revocation data of the application (see IRevocationDataProvider), asked before the network. The default value is null.

public static bool UseNetwork { get; set; }

Gets or sets a value indicating whether the OCSP responders and the CRL distribution points are contacted. The default value is true. When it is false, only the data added with RevocationCache.AddCrl and RevocationCache.AddOcspResponse and the data of the RevocationCache.Provider are used (a server without Internet access).

Methods
public static void AddCrl(byte[] crl)

Adds a CRL (DER or PEM) obtained by the application, used for the certificates issued by its issuer while it is current (it is validated as a downloaded CRL: issuer, signature, validity). It is kept until RevocationCache.Clear.

crl
The CRL.

Exceptions.

  • ArgumentException: The data is not a CRL.
public static void AddOcspResponse(byte[] response)

Adds an OCSP response (DER OCSPResponse or BasicOCSPResponse) obtained by the application, used for its certificate while it is current (it is validated as a downloaded response: certificate, responder, signature, validity). It is kept until RevocationCache.Clear.

response
The OCSP response.

Exceptions.

  • ArgumentException: The data is not a successful basic OCSP response.
public static void Clear()

Removes all the cached OCSP responses, CRLs and failures, and the data added with RevocationCache.AddCrl and RevocationCache.AddOcspResponse.

public static IReadOnlyList<MissingValidationData> Prefetch(X509Certificate2 signingCertificate, TimestampSettings timestamping = null)

Downloads into the cache the revocation data of the certificate chain of a signing certificate (and of the time-stamping authority of a time-stamping server), before the first signature of a batch: a missing data or a revoked certificate is reported at once. The data is obtained as for the default LTV level (IncludeOcspOnly): the OCSP response of the signing certificate (its CRL when the OCSP responder does not answer) and the CRLs of the CA certificates. The long term signatures still request new OCSP responses (chain of the signer and of the time-stamping authority) after each time-stamp (see RevocationCache); the prefetched ones are used when they cannot be obtained (e.g. with RevocationCache.UseNetwork set to false).

signingCertificate
The signing certificate.
timestamping
The time-stamping settings of the signatures (a time-stamp is requested to know the certificate of the time-stamping authority), or null.

Returns. The certificates whose revocation data could not be obtained (empty when everything is available).

Exceptions.

ValidationDataException class

Namespace: SignLib.Certificates · Assembly: SignLib.dll

public class ValidationDataException : CryptographicException, ISerializable

The exception thrown when a long term signature (PAdES-LT/LTA, CAdES-LT/LTA/C/XL/A, XAdES-LT/LTA) is requested and the revocation data (OCSP response or CRL) of a certificate of the signer or of the time-stamping authority cannot be obtained. No signed document is produced: a signature without this data would not be a long term signature. To create the signature anyway, with the data that could be obtained (the behaviour of the earlier versions of SignLib), set the AllowIncompleteValidationData property of the signature class to true.

Constructors
public ValidationDataException(IList<MissingValidationData> missingData)

Initializes a new instance of the ValidationDataException class.

missingData
The certificates without revocation data.
Properties
public IReadOnlyList<MissingValidationData> MissingData { get; }

Gets the certificates without revocation data, with the reasons.

X509CertificateGenerator class

Namespace: SignLib.Certificates · Assembly: SignLib.dll

public class X509CertificateGenerator

Generates X.509 certificates (RSA or ECDSA keys): self-signed certificates, certificates issued by a root (CA) certificate, and certificates issued for a certificate signing request (CSR).

Constructors
public X509CertificateGenerator(string librarySerialNumberLicense)

Initializes a new instance of the X509CertificateGenerator class.

librarySerialNumberLicense
The serial number provided to register the library.
Properties
public EllipticCurve EllipticCurve { get; set; }

Gets or sets the elliptic curve of an ECDSA key pair. The default value is EllipticCurve.NistP256. Not used for RSA keys.

public Extensions Extensions { get; set; }

Gets or sets the extensions of the certificate (key usages, CRL distribution points, policies, etc.).

public string FriendlyName { get; set; }

Gets or sets the friendly name of the certificate in the PFX file: the name that Windows shows for the certificate (e.g. in the certificate store). The default value is an empty string: Windows then shows the unique name of the private key as the name of the certificate. The private key of the PFX file always has a unique name, which Windows uses as the name of the key container when the certificate is installed in a certificate store, so certificates with the same friendly name do not share a key.

public KeyAlgorithm KeyAlgorithm { get; set; }

Gets or sets the algorithm of the generated key pair: RSA (default), DSA or ECDSA.

public KeySize KeySize { get; set; }

Gets or sets the size of an RSA or DSA key pair. The default value is KeySize.KeySize2048Bit. A DSA key can have 1024, 2048 or 3072 bits. Not used for ECDSA keys (the size is given by X509CertificateGenerator.EllipticCurve). KeySize512Bit and KeySize1024Bit are obsolete (insecure).

public long SerialNumber { get; set; }

Gets or sets the serial number of the certificate (a positive value). When it is not set, a random 128-bit serial number is generated.

public SignatureAlgorithm SignatureAlgorithm { get; set; }

Gets or sets the hash algorithm of the certificate signature. The default value is SignatureAlgorithm.SHA256WithRSA. Only the hash algorithm is taken from this value: the signature is RSA, DSA or ECDSA according to the key of the issuer (the root certificate, or the certificate itself when it is self-signed), e.g. SHA256WithRSA with an ECDSA issuer creates an ecdsa-with-SHA256 signature. A DSA issuer key of 2048 or 3072 bits requires SHA-256 or a longer hash (not SHA-1).

public string Subject { get; set; }

Gets or sets the subject of the certificate (e.g. "CN=John Doe, O=Company, C=RO"). The subject can also be built with X509CertificateGenerator.AddToSubject.

public string SubjectAlternativeNames { get; set; }

Gets or sets the Subject Alternative Names, comma separated. The type of each name is detected from its value: an IPv4 or IPv6 address is added as iPAddress, an absolute URI (e.g. https://www.example.com/ or urn:...) as uniformResourceIdentifier, a value that contains '@' as rfc822Name (email) and any other value as dNSName. Use X509CertificateGenerator.AddSubjectAlternativeName to set the type explicitly (e.g. for an URI that contains a comma).

public DateTime ValidFrom { get; set; }

Gets or sets the date, in local time, on which the certificate becomes valid. The default value is the current date and time.

public DateTime ValidTo { get; set; }

Gets or sets the date, in local time, after which the certificate is no longer valid. The default value is X509CertificateGenerator.ValidFrom + 1 year (at most X509CertificateGenerator.ValidFrom + 30 days on the demo version). A certificate issued by a loaded root (CA) certificate is valid at most until the end of the validity of the issuer: a later ValidTo is set to it.

Methods
public void AddSubjectAlternativeName(SubjectAlternativeNameType nameType, string value)

Adds a Subject Alternative Name of the given type to the certificate (in addition to the names of the X509CertificateGenerator.SubjectAlternativeNames property).

nameType
The type of the name.
value
The name: a DNS name (e.g. www.example.com), an IPv4 or IPv6 address, an email address or an absolute URI.

Exceptions.

  • ArgumentException: The name is empty or it is not valid for its type.
public void AddToSubject(SubjectType subjectType, string subjectTypeValue)

Adds an attribute to the subject of the certificate (e.g. E=email@email.com, L=My locality). The attributes are used when X509CertificateGenerator.Subject is not set, in the order in which they are added.

subjectType
The type of the attribute.
subjectTypeValue
The value of the attribute.
public byte[] GenerateCertificate(string PFXFilePassword)

Generates a certificate and its key pair.

PFXFilePassword
The password of the generated PFX file.

Returns. The PFX file with the certificate and its private key.

Exceptions.

  • CryptographicException: The certificate cannot be generated.
public byte[] GenerateCertificate(string PFXFilePassword, bool isRootCertificate)

Generates a certificate and its key pair.

PFXFilePassword
The password of the generated PFX file.
isRootCertificate
True to generate a CA certificate (a root certificate or, when a root certificate is loaded, an intermediate CA certificate).

Returns. The PFX file with the certificate, its private key and, when a root certificate is loaded, the root certificate.

Exceptions.

  • CryptographicException: The certificate cannot be generated.
public byte[] GenerateCertificateFromCSR(string CSR)

Issues a certificate for a certificate signing request (CSR), signed by the loaded root certificate.

CSR
The certificate signing request (PKCS#10), PEM encoded.

Returns. The DER encoded certificate.

Exceptions.

  • CryptographicException: The CSR is not valid or no root certificate is loaded.
public void LoadRootCertificate(byte[] RootPFXCertificate, string PFXFilePassword)

Loads the root (CA) certificate used to sign the generated certificates.

RootPFXCertificate
The content of the PFX file of the root certificate.
PFXFilePassword
The password of the PFX file.

Exceptions.

  • CryptographicException: The PFX file has no private key or no certificate chain.

CertificateEnhancedKeyUsage enum

Namespace: SignLib.Certificates · Assembly: SignLib.dll

public enum CertificateEnhancedKeyUsage

Enhanced (extended) key usages of a certificate (the extended key usage extension, RFC 5280 4.2.1.12).

MemberValueDescription
AnyPurpose0Any extended key usage.
ClientAuthentication1TLS client authentication.
CodeSigning2Code signing.
SecureEmail3Email protection (S/MIME).
IpsecEndSystem4IPsec end system.
IpsecTunnel5IPsec tunnel.
IpsecUser6IPsec user.
OcspSigning7Signing of OCSP responses.
ServerAuthentication8TLS server authentication.
SmartcardLogon9Windows smart card logon.
TimeStamping10Signing of RFC 3161 time-stamps.
DocumentSigning11Document signing (Microsoft, 1.3.6.1.4.1.311.10.3.12).
NetscapeServerGatedCrypto12Netscape Server Gated Crypto (nsSGC), a legacy step-up of the encryption of old browsers.
MicrosoftServerGatedCrypto13Microsoft Server Gated Crypto (msSGC), a legacy step-up of the encryption of old browsers.

CertificateKeyUsage enum

Namespace: SignLib.Certificates · Assembly: SignLib.dll

public enum CertificateKeyUsage

Key usages of a certificate (the key usage extension, RFC 5280 4.2.1.3).

MemberValueDescription
DataEncipherment16The public key is used to encipher user data, other than cryptographic keys.
DigitalSignature128The public key is used to verify digital signatures, other than signatures on certificates and CRLs (e.g. authentication).
KeyEncipherment32The public key is used for key transport (not allowed for ECDSA keys).
NonRepudiation64The public key is used to verify digital signatures that provide a non-repudiation service (content commitment), e.g. the signatures of documents.
CRLSigning2The public key is used to verify the signatures of CRLs.
CertificateSigning4The public key is used to verify the signatures of certificates.
KeyAgreement8The public key is used for key agreement.
EncipherOnly1With KeyAgreement: the public key may be used only to encipher data while performing key agreement.
DecipherOnly32768With KeyAgreement: the public key may be used only to decipher data while performing key agreement.

CertificateStatus enum

Namespace: SignLib.Certificates · Assembly: SignLib.dll

public enum CertificateStatus

Status of a certificate, returned by DigitalCertificate.VerifyDigitalCertificate.

MemberValueDescription
Valid0The certificate is valid (in its validity period, or not revoked).
Revoked1The certificate is revoked.
Expired2The certificate is not in its validity period (expired or not yet valid).
Unknown3The status cannot be determined (e.g. the OCSP responder or the CRL is not available).
NotPresent4The certificate has no OCSP responder or no CRL.

CertificateTrustStatus enum

Namespace: SignLib.Certificates · Assembly: SignLib.dll

public enum CertificateTrustStatus

The result of the validation of a certificate by CertificateValidator. When several problems are found, the most serious one is reported (in the order of this list, from InvalidChain); all of them are in CertificateValidationResult.Problems.

MemberValueDescription
Trusted0The certificate chain ends at a trusted root, every certificate of the chain was valid at the validation time, none was revoked, and the certificate can be used for signatures.
InvalidChain1The chain cannot be built (an issuer certificate is missing) or it is not valid (e.g. a certificate is not signed by its issuer, or an issuer is not a certification authority).
NotTimeValid2A certificate of the chain was not valid at the validation time (expired or not yet valid).
Revoked3A certificate of the chain was revoked before the validation time.
InvalidKeyUsage4The key usage of the certificate does not allow signatures (digitalSignature or nonRepudiation).
UntrustedRoot5The chain is valid, but its root is not trusted (it is neither a trusted root of Windows nor one of CertificateValidationSettings.TrustedRoots).
RevocationUnknown6The chain is valid and trusted, but the revocation status of a certificate cannot be determined (no OCSP response or CRL that can be trusted).

DigitalCertificateSearchCriteria enum

Namespace: SignLib.Certificates · Assembly: SignLib.dll

public enum DigitalCertificateSearchCriteria

Criterion used to find a certificate in the Windows certificate store (e.g. CommonNameCN searches the CN= field of the subject).

MemberValueDescription
CommonNameCN0The "CN=" field of the subject.
OrganizationO1The "O=" field of the subject.
OrganizationUnitOU2The "OU=" field of the subject.
EmailE3The "E=" field of the subject.
LocalityL4The "L=" field of the subject.
CountryC5The "C=" field of the subject.
StateS6The "S=" field of the subject.
TitleT7The "T=" field of the subject.
Thumbprint8The thumbprint of the certificate.
SerialNumber9The serial number of the certificate.

EllipticCurve enum

Namespace: SignLib.Certificates · Assembly: SignLib.dll

public enum EllipticCurve

Elliptic curve of an ECDSA key pair (named curves, RFC 5480 and RFC 5639).

MemberValueDescription
NistP2560NIST P-256 (secp256r1, prime256v1), 256 bits. The most widely supported curve.
NistP3841NIST P-384 (secp384r1), 384 bits.
NistP5212NIST P-521 (secp521r1), 521 bits.
BrainpoolP256r13Brainpool P-256r1 (RFC 5639), 256 bits.
BrainpoolP384r14Brainpool P-384r1 (RFC 5639), 384 bits.
BrainpoolP512r15Brainpool P-512r1 (RFC 5639), 512 bits.

KeyAlgorithm enum

Namespace: SignLib.Certificates · Assembly: SignLib.dll

public enum KeyAlgorithm

Algorithm of the key pair generated by X509CertificateGenerator.

MemberValueDescription
RSA0An RSA key, of the size set by X509CertificateGenerator.KeySize.
ECDSA1An ECDSA key, on the curve set by X509CertificateGenerator.EllipticCurve.
DSA2A DSA key, of the size set by X509CertificateGenerator.KeySize: 1024 bits (FIPS 186-2, 160-bit subgroup), 2048 or 3072 bits (FIPS 186-3, 256-bit subgroup). A DSA key can only sign: the key usages are limited to digitalSignature, nonRepudiation, keyCertSign and cRLSign (RFC 3279, 2.3.2).

KeySize enum

Namespace: SignLib.Certificates · Assembly: SignLib.dll

public enum KeySize

Size of an RSA or DSA key pair, in bits. A DSA key can have 1024, 2048 or 3072 bits.

MemberValueDescription
KeySize512Bit obsolete512512 bits. Obsolete: 512-bit RSA keys are insecure and are rejected by current validators.
KeySize1024Bit obsolete10241024 bits. Obsolete: 1024-bit RSA keys are considered weak and are rejected by current validators.
KeySize2048Bit20482048 bits. Recommended for user certificates.
KeySize3072Bit30723072 bits.
KeySize4096Bit40964096 bits. Recommended for CA certificates.
KeySize8192Bit81928192 bits.

QcSemanticsIdentifier enum

Namespace: SignLib.Certificates · Assembly: SignLib.dll

public enum QcSemanticsIdentifier

Semantics identifier of the serialNumber or organizationIdentifier of the subject (ETSI EN 319 412-1).

MemberValueDescription
None0The semantics identifier is not added.
NaturalPerson1Natural person identifier (id-etsi-qcs-semanticsId-Natural), e.g. serialNumber=PNORO-1234567890123.
LegalPerson2Legal person identifier (id-etsi-qcs-semanticsId-Legal), e.g. organizationIdentifier=VATRO-12345678.
EidasNaturalPerson3eIDAS natural person identifier (id-etsi-qcs-semanticsId-eIDASNatural).
EidasLegalPerson4eIDAS legal person identifier (id-etsi-qcs-semanticsId-eIDASLegal).

QualifiedCertificateType enum

Namespace: SignLib.Certificates · Assembly: SignLib.dll

public enum QualifiedCertificateType

Type of a qualified certificate (QcType statement, ETSI EN 319 412-5).

MemberValueDescription
None0The QcType statement is not added.
ESign1Certificate for electronic signatures (id-etsi-qct-esign).
ESeal2Certificate for electronic seals (id-etsi-qct-eseal).
Web3Certificate for website authentication (id-etsi-qct-web).

RevocationCheckMode enum

Namespace: SignLib.Certificates · Assembly: SignLib.dll

public enum RevocationCheckMode

How CertificateValidator checks the revocation status of the certificates of a chain.

MemberValueDescription
None0The revocation status is not checked.
Ocsp1OCSP only.
Crl2CRL only.
OcspThenCrl3OCSP, then the CRL when OCSP gives no status. The default value.

RevocationDataSource enum

Namespace: SignLib.Certificates · Assembly: SignLib.dll

public enum RevocationDataSource

The source of the revocation status of a certificate, in CertificateValidationResult.RevocationSources.

MemberValueDescription
None0No revocation status was found.
Settings1An OCSP response or a CRL of the settings (CertificateValidationSettings.OcspResponses / Crls).
Signature2The validation data embedded in the signature (e.g. the document security store of a PDF document, the revocation data of a CAdES-LT signature, the RevocationValues of a XAdES-LT signature).
Online3An OCSP responder or a CRL distribution point of the certificate (UseOnlineRevocation).

SignatureAlgorithm enum

Namespace: SignLib.Certificates · Assembly: SignLib.dll

public enum SignatureAlgorithm

Algorithm of the certificate signature. Only the hash algorithm is taken from this value: the signature is RSA, DSA or ECDSA according to the key of the issuer.

MemberValueDescription
SHA1WithRSA0SHA-1. Not recommended: SHA-1 is no longer considered secure for certificate signatures.
SHA256WithRSA1SHA-256.
SHA384WithRSA2SHA-384.
SHA512WithRSA3SHA-512.
SHA256WithECDSA4SHA-256 (ecdsa-with-SHA256 with an ECDSA issuer key).
SHA384WithECDSA5SHA-384 (ecdsa-with-SHA384 with an ECDSA issuer key).
SHA512WithECDSA6SHA-512 (ecdsa-with-SHA512 with an ECDSA issuer key).
SHA1WithDSA7SHA-1 (id-dsa-with-sha1 with a DSA issuer key). Only for DSA keys of 1024 bits: a larger DSA key (2048 or 3072 bits) needs SHA-256, see SignatureAlgorithm.SHA256WithDSA.
SHA256WithDSA8SHA-256 (dsa-with-sha256 with a DSA issuer key).

SubjectAlternativeNameType enum

Namespace: SignLib.Certificates · Assembly: SignLib.dll

public enum SubjectAlternativeNameType

Type of a Subject Alternative Name.

MemberValueDescription
DnsName0DNS name (dNSName), e.g. www.example.com.
IPAddress1IPv4 or IPv6 address (iPAddress).
Email2Email address (rfc822Name).
Uri3Absolute URI (uniformResourceIdentifier), e.g. https://www.example.com/.

SubjectType enum

Namespace: SignLib.Certificates · Assembly: SignLib.dll

public enum SubjectType

Attribute types of the subject of a certificate (see X509CertificateGenerator.AddToSubject).

MemberValueDescription
C0Country (C), a two-letter ISO 3166 code.
E1Email address (E).
L2Locality name (L).
O3Organization name (O).
T4Title (T).
CN5Common name (CN).
DC6Domain component (DC).
OU7Organizational unit name (OU).
ST8State or province name (ST).
UID9User ID (UID, LDAP).
STREET10Street address (STREET).
PSEUDONYM11Pseudonym (RFC 3039).
NAME12Name.
EMAILADDRESS13Email address (PKCS#9 emailAddress, an IA5String).
SERIALNUMBER14Serial number of the subject (SERIALNUMBER), e.g. PNORO-1234567890123.
SURNAME15Surname.
GIVENNAME16Given name.
INITIALS17Initials.

VerificationType enum

Namespace: SignLib.Certificates · Assembly: SignLib.dll

public enum VerificationType

Type of the verification of a certificate (see DigitalCertificate.VerifyDigitalCertificate).

MemberValueDescription
LocalTime0The validity period of the certificate, compared with the local time.
OCSP1The revocation status from the OCSP responder of the certificate.
CRL2The revocation status from the HTTP CRL of the certificate.
LDAP3The revocation status from the LDAP CRL of the certificate (supported on Windows).

18.8 Namespace SignLib.Timestamping

TypeDescription
TimestampAccuracy classAccuracy of the time of a time-stamp (RFC 3161 Accuracy): the time deviation around the time of the time-stamp.
TimestampClient classCreates RFC 3161 time-stamps for files and data: time-stamp responses (.TSR), time-stamp tokens (.TST) or Time Stamped Data files with the embedded content (.TSD, RFC 5544).
TimestampInfo classInformation about a time-stamp: a time-stamp response (.TSR), a time-stamp token (.TST) or a Time Stamped Data file (.TSD, RFC 5544).
TimestampSettings classSettings of the time-stamping server (RFC 3161) used to time-stamp signatures and documents.
TimestampFormat enumFormat of the time-stamps created by TimestampClient.

TimestampAccuracy class

Namespace: SignLib.Timestamping · Assembly: SignLib.dll

public class TimestampAccuracy

Accuracy of the time of a time-stamp (RFC 3161 Accuracy): the time deviation around the time of the time-stamp. Each value is null when it is not set by the time-stamping server.

Properties
public string Microseconds { get; }

Gets the microseconds of the accuracy.

public string Milliseconds { get; }

Gets the milliseconds of the accuracy.

public string Seconds { get; }

Gets the seconds of the accuracy.

TimestampClient class

Namespace: SignLib.Timestamping · Assembly: SignLib.dll

public class TimestampClient

Creates RFC 3161 time-stamps for files and data: time-stamp responses (.TSR), time-stamp tokens (.TST) or Time Stamped Data files with the embedded content (.TSD, RFC 5544).

Constructors
public TimestampClient(string librarySerialNumberLicense)

Initializes a new instance of the TimestampClient class.

librarySerialNumberLicense
The serial number provided to register the library.
Properties
public TimestampFormat TimestampFormat { get; set; }

Gets or sets the format of the result of TimestampClient.ObtainTimestamp. The default value is TimestampFormat.DetachedTimestamp (.TSR file).

public TimestampSettings TimeStamping { get; set; }

Gets or sets the settings of the time-stamping server.

Methods
public byte[] ObtainTimestamp(byte[] dataToBeTimestamped)

Time-stamps data.

dataToBeTimestamped
The data to time-stamp.

Returns. The time-stamp, in the format set by TimestampClient.TimestampFormat.

Exceptions.

  • WebException: The time-stamping server is not available or rejected the request.
public byte[] ObtainTimestamp(string fileToBeTimestamped)

Time-stamps a file.

fileToBeTimestamped
The path of the file to time-stamp.

Returns. The time-stamp, in the format set by TimestampClient.TimestampFormat. A .TSD file also contains the content and the name of the file.

Exceptions.

  • WebException: The time-stamping server is not available or rejected the request.

TimestampInfo class

Namespace: SignLib.Timestamping · Assembly: SignLib.dll

public class TimestampInfo

Information about a time-stamp: a time-stamp response (.TSR), a time-stamp token (.TST) or a Time Stamped Data file (.TSD, RFC 5544).

Constructors
public TimestampInfo(byte[] timestampToken)

Initializes a new instance of the TimestampInfo class from a time-stamp token.

timestampToken
The encoded time-stamp token (RFC 3161 TimeStampToken).
Properties
public TimestampAccuracy Accuracy { get; }

Gets the accuracy of the time of the time-stamp.

public Oid HashAlgorithm { get; }

Gets the hash algorithm of the time-stamped data (SHA-1, SHA-256, etc.).

public bool IsQualifiedTimestamp { get; }

Gets a value indicating whether the time-stamp token declares itself as a qualified electronic time-stamp (ETSI EN 319 422): the qcStatements extension (1.3.6.1.5.5.7.1.3) of TSTInfo contains the esi4-qtstStatement-1 statement (0.4.0.19422.1.1). The qualified status itself is given by the EU Trusted Lists: a qualified time-stamping server may issue time-stamps without this statement.

public bool IsTimestampAltered { get; }

Gets a value indicating whether the signature of the time-stamp token is not valid (the token was altered).

public string Nonce { get; }

Gets the nonce of the time-stamp request, or null when the request had no nonce.

public byte[] OriginalDataHash { get; }

Gets the hash of the time-stamped data (the message imprint of the time-stamp).

public Oid Policy { get; }

Gets the policy of the time-stamping server (e.g. 1.3.6.1.4.1.13762.3).

public string SerialNumber { get; }

Gets the serial number of the time-stamp.

public DateTime SignatureTime { get; }

Gets the time of the time-stamp, in UTC.

public byte[] TimestampedDataContent { get; }

Gets, for a Time Stamped Data file (.TSD), the original (time-stamped) content embedded in the file, or null when the content is not embedded.

public string TimestampedDataFileName { get; }

Gets, for a Time Stamped Data file (.TSD), the original file name, or null when it is not set.

public byte[] TimestampToken { get; }

Gets the time-stamp token.

public X509Certificate2 TsaCertificate { get; }

Gets the certificate of the time-stamping server (the certificate that signed the time-stamp token), or null when the token does not contain it.

public string TsaServerName { get; }

Gets the name of the time-stamping server, or null when it is not set in the time-stamp.

Methods
public static TimestampInfo GetInfoFromTsaResponse(byte[] timestampToken)

Reads a time-stamp file: a time-stamp response (.TSR), a time-stamp token (.TST) or a Time Stamped Data file (.TSD, RFC 5544). For a .TSD file, TimestampInfo.TimestampedDataContent and TimestampInfo.TimestampedDataFileName are also set.

timestampToken
The content of the time-stamp file.

Returns. The information about the time-stamp.

public static bool IsTsaReponseFileValid(byte[] originalFile, byte[] timestampToken)

Verifies a time-stamp file: a time-stamp response (.TSR), a time-stamp token (.TST) or a Time Stamped Data file (.TSD). If the file was changed or the time-stamp is altered, an exception is thrown.

originalFile
The original (time-stamped) file. For a .TSD file that contains the original content it can be null; when it is set, it must be identical with the embedded content.
timestampToken
The content of the time-stamp file.

Returns. True if the time-stamp is valid.

Exceptions.

  • CryptographicException: The time-stamp is altered or it does not match the original file.

TimestampSettings class

Namespace: SignLib.Timestamping · Assembly: SignLib.dll

public class TimestampSettings

Settings of the time-stamping server (RFC 3161) used to time-stamp signatures and documents.

Constructors
public TimestampSettings()

Initializes a new instance of the TimestampSettings class.

Properties
public X509Certificate2 AuthenticationCertificate { get; set; }

Gets or sets the certificate used for TLS client authentication to the time-stamping server, or null.

public HashAlgorithm HashAlgorithm { get; set; }

Gets or sets the hash algorithm of the time-stamp request. The default value is SHA256.

public string Password { get; set; }

Gets or sets the password for the HTTP basic authentication to the time-stamping server.

public Oid PolicyOid { get; set; }

Gets or sets the policy requested from the time-stamping server. Set it only when the server requires it.

public int ServerTimeout { get; set; }

Gets or sets the timeout of the time-stamping server, in milliseconds. The default value is 20000 milliseconds (20 seconds).

public Uri ServerUrl { get; set; }

Gets or sets the URL of the time-stamping server (e.g. https://ca.signfiles.com/tsa/get.aspx).

public bool UseNonce { get; set; }

Gets or sets a value indicating whether a nonce is added to the time-stamp request, to match the response with the request. The default value is true.

public string UserName { get; set; }

Gets or sets the user name for the HTTP basic authentication to the time-stamping server, or null.

TimestampFormat enum

Namespace: SignLib.Timestamping · Assembly: SignLib.dll

public enum TimestampFormat

Format of the time-stamps created by TimestampClient.

MemberValueDescription
DetachedTimestamp0The time-stamp response (RFC 3161 TimeStampResp) is saved in a separate file (.TSR file).
EmbeddedTimestamp1The time-stamp is saved together with the original file, in the Time Stamped Data format of RFC 5544 (.TSD file). The original file name is saved in the MetaData of the file.
TimestampToken2Only the time-stamp token (RFC 3161 TimeStampToken, a CMS SignedData) is saved in a separate file (.TST file), without the response status. This is the detached time-stamp format accepted by validators like EU DSS. Italian verifiers (e.g. VOL of Consiglio Nazionale del Notariato) expect a .TSR (TimestampFormat.DetachedTimestamp) or a .TSD (TimestampFormat.EmbeddedTimestamp) file instead.

Appendix A. Default values and limits

A.1 Default values of the settings

The values that a property has until you set it:

ClassDefaults
PdfSignatureSignatureStandard = Default (PKCS#7); HashAlgorithm = SHA256; PadesLtvLevel = IncludeOcspOnly; MaxCrlSize 1 MB; AllowIncompleteValidationData = false; CertifySignature = NotCertified; VisibleSignature = true; SignaturePosition = TopRight (a rectangle of 100 × 50 points, 50 points from the edges); SignaturePage = 1; SignaturePages empty; SignatureAppearsOnAllPages = false; SignatureImageType = ImageAndText; FontName = Helvetica; OldStyleAdobeSignature = false; SignatureByteBlockSize = 20480; no encryption; no time-stamp (TimeStamping.ServerUrl = null).
CadesSignatureSignatureStandard = CadesBes; HashAlgorithm = SHA256; IsDetachedSignature = false; LtvLevel = IncludeOcspOnly; MaxCrlSize 20 MB; AllowIncompleteValidationData = false; CoSignExistingSignature = true (a CMS signature given as data is co-signed); no time-stamp.
XmlSignatureHashAlgorithm = SHA256; SignatureType = Default (Canonical XML 1.0); IncludeKeyInfo = true; IncludeSignatureCertificate = true; PreserveWhitespace = true.
XadesSignatureSignatureStandard = XadesB; SignaturePackaging = Enveloped; HashAlgorithm = SHA256; LtvLevel = IncludeOcspOnly; MaxCrlSize 1 MB; AllowIncompleteValidationData = false; CommitmentType = None; no production place; no policy; no time-stamp.
OfficeSignatureSignatureStandard = XadesB; HashAlgorithm = SHA256; LtvLevel = IncludeOcspOnly; MaxCrlSize 1 MB; AllowIncompleteValidationData = false; CommitmentType = None; SignatureLine = null (invisible).
AsicSignatureSignatureStandard = XadesB; HashAlgorithm = SHA256; LtvLevel = IncludeOcspOnly; MaxCrlSize 1 MB; AllowIncompleteValidationData = false; CommitmentType = None.
TimestampSettingsUseNonce = true; HashAlgorithm = SHA256; ServerTimeout = 20000 ms; no server, no authentication, no policy.
TimestampClientTimestampFormat = DetachedTimestamp (.tsr).
DigitalCertificateTimeout = 20000 ms (the downloads of the CRLs, of the OCSP responses and of documents; the same setting as NetworkSettings.RevocationTimeout).
NetworkSettingsProxy = null (the proxy of the system); RevocationTimeout = 20000 ms; MaxConnectionsPerServer = 16 (.NET Framework only); MaxResponseSize = 52428800 (50 MB); MaxRedirects = 3; BlockPrivateAddresses = false; AllowLegacyTls = true. section 4.10
SecurityLimitsAllowXmlDtd = false; MaxZipEntries = 10000; MaxZipEntrySize 1 GB; MaxZipTotalSize 2 GB; MaxCompressionRatio = 1000 (for the entries larger than 1 MB). section 4.11
XmlSignatureVerificationPolicyRejectSha1 = false.
RevocationCacheEnabled = true; OcspMaxAge 5 minutes; CrlMaxAge 1 hour; MaxCrlCacheSize 100 MB; FailureRetention 60 seconds; Provider = null; UseNetwork = true. section 12.5
CertificateCacheEnabled = true; MaxAge 1 hour; KeepSmartCardKeys = true. section 5.5
X509CertificateGeneratorValidFrom = now; ValidTo = one year later (30 days in the demo version); KeyAlgorithm = RSA; KeySize = KeySize2048Bit; EllipticCurve = NistP256; SignatureAlgorithm = SHA256WithRSA (only the hash is taken from it); random 128-bit serial number; no extensions.
PdfEncrypt, PdfEncryptionSettingsEncryptionMethod = NoEncryption.

A.2 Limits and what is not supported

AreaLimit in SignLib 8.6
Hash algorithmsSHA-1, SHA-256, SHA-384, SHA-512. SHA-1 does not create new XML, XAdES, Office and ASiC-E signatures (it verifies them).
Key typesRSA and ECDSA for signing. XML, XAdES, Office and ASiC-E: RSA and ECDSA only. RSA signatures are PKCS#1 v1.5 (not PSS).
Verification of signatures created by other applicationsPDF and CAdES: also RSASSA-PSS, ECDSA with SHA-224, SHA-3 and EdDSA signatures. A signature whose algorithm is not supported is reported with SignatureIsValid = false and SignatureAlgorithmNotSupported = true.
PDF encryptionRC4 40/128 bit and AES-128. AES-256 (PDF 2.0) is not supported. A signed document cannot be encrypted by PdfSignature.
PDF document sizeLess than 2 GB, for the loaded document and for the signed document (IOException otherwise). section 6.12
PDF signature formatsPKCS#7 detached, PAdES B-B, B-LT, B-LTA; document time-stamps. A document has one certification signature, the first.
CAdESAll the levels of CadesSignatureStandard. CadesSignature.AddArchiveTimestamp renews CAdES-LTA signatures (not CAdES-A). No size limit for the signed document (tested with 5 GB, from streams: section 7.6).
XAdESB-B, B-T, B-LT, B-LTA, enveloped and detached.
OfficeOffice Open XML documents; levels B, T, LT (not LTA). Visible signatures: Word documents, Windows only. XPS is not supported.
ASiC-EXAdES signatures. CAdES signature files in a container are not supported. A created container has at most 65535 files and 4 GB.
Containers and XML documents that are read (SecurityLimits)ASiC-E containers and Office packages: at most 10000 entries, 1 GB for an entry and 2 GB in all (uncompressed), a compression ratio of at most 1000 for the entries larger than 1 MB, no duplicate entries (SecurityLimitException). XML documents: no DTD (XmlException), unless AllowXmlDtd is true; external entities are never loaded. All the values can be changed. section 4.11
Network responses (NetworkSettings)At most 50 MB for a time-stamp, an OCSP response, a CRL or a downloaded document; at most 3 redirects; HTTPS is never redirected to HTTP.
Time-stampsRFC 3161 over HTTP or HTTPS; the formats .tsr, .tst and .tsd.
ThreadsThe signature objects are not thread-safe; UseExternalSignatureProvider and SmartCardPin are thread-local.
MemoryThe documents are processed in memory: the memory needed is a multiple of the size of the document. The PDF and CAdES signatures can be created from streams, without the whole document in memory (section 15.7). The library writes no temporary files.
Platforms.NET 8, .NET 9, .NET 10, .NET 11 (one build each); .NET Framework 4.6.2 to 4.7.x (the netframework4.6.2 build) and .NET Framework 4.8 and 4.8.1 (the netframework4.8 build). Windows-only functions: section 1.2.

Appendix B. OIDs, URIs and standards

B.1 Identifiers that you meet in the API

IdentifierValue
Hash algorithms (OIDs of IExternalSignature.ApplySignature, of policies and of time-stamps)SHA-1 1.3.14.3.2.26; SHA-256 2.16.840.1.101.3.4.2.1; SHA-384 2.16.840.1.101.3.4.2.2; SHA-512 2.16.840.1.101.3.4.2.3
PDF signature filters (/SubFilter)adbe.pkcs7.detached (PdfSignatureStandard.Default); ETSI.CAdES.detached (Pades, PadesLT, PadesLTA); ETSI.RFC3161 (a document time-stamp)
XMLDSig canonicalization (XmlSignatureType)Default: http://www.w3.org/TR/2001/REC-xml-c14n-20010315; DefaultWithComments: the same with #WithComments; Exclusive: http://www.w3.org/2001/10/xml-exc-c14n#; ExclusiveWithComments: the same with WithComments
XML signature methodshttp://www.w3.org/2001/04/xmldsig-more#rsa-sha256, rsa-sha384, rsa-sha512; http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256, ecdsa-sha384, ecdsa-sha512
XML digest methodshttp://www.w3.org/2001/04/xmlenc#sha256, http://www.w3.org/2001/04/xmldsig-more#sha384, http://www.w3.org/2001/04/xmlenc#sha512
XAdES commitment types (XadesCommitmentType)http://uri.etsi.org/01903/v1.2.2#ProofOfOrigin, #ProofOfReceipt, #ProofOfDelivery, #ProofOfSender, #ProofOfApproval, #ProofOfCreation
CAdES unsigned attributessignature-time-stamp 1.2.840.113549.1.9.16.2.14; complete-certificate-references ...2.21; complete-revocation-references ...2.22; certificate-values ...2.23; revocation-values ...2.24; escTimeStamp ...2.25; archive-time-stamp-v3 0.4.0.1733.2.4
Extended key usages (CertificateEnhancedKeyUsage)DocumentSigning 1.3.6.1.4.1.311.10.3.12; SecureEmail 1.3.6.1.5.5.7.3.4; ClientAuthentication 1.3.6.1.5.5.7.3.2; ServerAuthentication 1.3.6.1.5.5.7.3.1; CodeSigning 1.3.6.1.5.5.7.3.3; TimeStamping 1.3.6.1.5.5.7.3.8; OcspSigning 1.3.6.1.5.5.7.3.9
Qualified certificates and time-stampsqcStatements extension 1.3.6.1.5.5.7.1.3; QCP-n-qscd policy 0.4.0.194112.1.2; qualified time-stamp statement (esi4-qtstStatement-1) 0.4.0.19422.1.1
Public key algorithmsRSA 1.2.840.113549.1.1.1; id-ecPublicKey 1.2.840.10045.2.1

B.2 Standards and specifications

DocumentTopic
Regulation (EU) No 910/2014 (eIDAS), as amendedElectronic identification and trust services.
ETSI EN 319 142-1 / -2PAdES: PDF advanced electronic signatures.
ETSI EN 319 122-1 / -2 (and ETSI TS 101 733)CAdES: CMS advanced electronic signatures.
ETSI EN 319 132-1 / -2 (and ETSI TS 101 903)XAdES: XML advanced electronic signatures.
ETSI EN 319 162-1 / -2ASiC: associated signature containers.
ETSI EN 319 412-1 ... -5Certificate profiles (identifiers, QCStatements).
ETSI EN 319 421, ETSI EN 319 422Time-stamping policy and profiles (qualified time-stamps).
ISO 32000-1, ISO 32000-2PDF 1.7 and PDF 2.0.
RFC 5652; RFC 5126Cryptographic Message Syntax (CMS); CMS advanced electronic signatures.
RFC 3161; RFC 5544Time-stamp protocol; Time Stamped Data (.tsd).
RFC 5280; RFC 6960X.509 certificates and CRLs; OCSP.
RFC 8017; RFC 5753; RFC 5480; RFC 4051; RFC 6931PKCS#1 (RSA); ECDSA in CMS; EC keys in X.509; ECDSA in XML signatures.
W3C XML Signature Syntax and Processing; Canonical XML 1.0; Exclusive XML Canonicalization 1.0XMLDSig.
ECMA-376 Part 2 (Open Packaging Conventions); [MS-OFFCRYPTO]Office package signatures.
PKCS #11 v2.40The interface of tokens and HSMs.

Appendix C. Glossary

TermMeaning
AdESAdvanced electronic signature: the formats PAdES, CAdES, XAdES of ETSI.
Archive time-stampA time-stamp over a signature and its validation data; the last element of the LTA level; it is renewed periodically.
ASiC-EAssociated Signature Container, Extended: a ZIP file with files and their XAdES signatures.
Attached / detached / envelopedWhere the signed data is: attached, in the signature file (.p7m); detached, outside it (.p7s, a detached XAdES file); enveloped, the signature is inside the signed XML document.
B-B, B-T, B-LT, B-LTAThe baseline levels of AdES signatures: basic, with a time-stamp, with long term validation data, with archive time-stamps.
CACertification authority: issues certificates.
CAdESCMS Advanced Electronic Signatures.
Canonicalization (C14N)The conversion of an XML document to a standard byte sequence before it is signed.
CMSCryptographic Message Syntax (RFC 5652), the successor of PKCS#7.
Certification signatureThe first signature of a PDF document, that says which changes are allowed later (DocMDP).
CRLCertificate revocation list: the list of the certificates that the CA revoked.
CSRCertificate signing request (PKCS#10): the request for a certificate, with the public key.
DERDistinguished Encoding Rules: the binary encoding of the ASN.1 structures of certificates and signatures.
DSSThe Digital Signature Service of the European Commission (a validation library and web application); not the document security store of PDF.
Document security store (/DSS)The part of a PDF document that holds the certificates and the revocation data of the long term signatures.
eIDASRegulation (EU) 910/2014 on electronic identification and trust services.
HSMHardware security module: a device that keeps keys and signs with them.
HashThe fixed-size digest of data (SHA-256, ...). A signature signs the hash.
LTVLong term validation: the signature contains what is needed to validate it later.
Message imprintThe hash that a time-stamp covers.
NonceA random number in a time-stamp request, repeated in the response.
OCSPOnline Certificate Status Protocol: a server that answers whether a certificate is revoked.
OIDObject identifier: a dotted number that identifies an algorithm, a policy or an extension.
PAdESPDF Advanced Electronic Signatures.
PFX / P12 / PKCS#12A file with a certificate, its private key and its chain, protected by a password.
PKCS#7The older name of CMS; the adbe.pkcs7.detached PDF signature is a CMS signature.
PKCS#11 (Cryptoki)The programming interface of the tokens and HSMs.
QSCDQualified signature (or seal) creation device.
QESQualified electronic signature: with a qualified certificate, created in a QSCD.
Signature policyA document that states the rules for the creation and the validation of a signature, identified by an OID and its hash.
Signature fieldThe form field of a PDF document that holds a signature.
ThumbprintThe SHA-1 hash of a certificate: a short identifier of it.
Time-stamp (.tsr, .tst, .tsd)A signed proof of the time of some data, from a TSA: a response (.tsr), a token (.tst), or the data with its time-stamp (.tsd).
TSATime-stamping authority.
Trusted listThe list of qualified trust service providers that a member state of the EU publishes.
XAdESXML Advanced Electronic Signatures.
XMLDSigThe W3C standard of XML signatures.

Every effort has been made to make this manual as complete and accurate as possible, but no warranty or fitness is implied. The information provided is on an “as is” basis. The author shall have neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this manual. The information about the eIDAS Regulation is a simplified explanation and it is not legal advice.

SignLib.dll is a single file: it contains the code of Secure Soft SRL and these open source components, compiled from their source code. Their licenses apply to these components only; the SignLib License Agreement does not limit the rights that they grant.

THIRD-PARTY-NOTICES.txt (in the folder License Agreement, and embedded in SignLib.dll as the resource SignLib.THIRD-PARTY-NOTICES.txt) lists all of them, with their copyright notices; the license texts are in the folder License Agreement\Third-Party Licenses. When you distribute SignLib.dll with your application, distribute THIRD-PARTY-NOTICES.txt with it, or include its content in the documentation of your application; the file also says where the source code of iTextSharp is available. The NuGet packages of Microsoft that the .NET builds use are not part of the download; they are licensed by the .NET Foundation and Contributors under the MIT license.

.NET, Windows, PowerShell, Visual Studio, Microsoft Office, Word, Excel, PowerPoint and Azure are trademarks of Microsoft Corporation. Adobe, Acrobat and Acrobat Reader are trademarks of Adobe Inc. All the other names are trademarks of their owners.