A signing server is often on an internal network, without Internet access, and it signs documents received from third parties. This C# sample configures the library for such a server: the revocation data comes from a folder instead of the network, the certificate is loaded once for many documents, and the limits protect the server against the documents that are read.

What the sample shows

  1. Process-wide settings, set once when the application starts: NetworkSettings (proxy, time-outs, maximum response size, no OCSP or CRL requests to private addresses), SecurityLimits (ZIP containers, XML documents with a DTD) and XmlSignatureVerificationPolicy.RejectSha1.
  2. The revocation cache without the network: RevocationCache.UseNetwork = false; the CRLs and OCSP responses copied to a folder are added with AddCrl and AddOcspResponse or read on demand by an IRevocationDataProvider; Prefetch checks, before the first document, that the revocation data of the signing certificate is available.
  3. The certificate cache: the certificate chain, the private key and the PFX file are loaded once for many documents (CertificateCache.MaxAge, Statistics).
  4. Signing without the network (PAdES, CAdES, XAdES and ASiC-E at level B-B) and the verification of the signed documents, as documents received from a third party. An XML document with a DTD is refused.

C# code: the settings of the library

static void ConfigureLibrary()
{
    // The network. A proxy server is used for all the HTTP requests of the library (time-stamps, OCSP, CRL, documents loaded
    // from a URL). null (the default) uses the proxy of the system.
    // NetworkSettings.Proxy = new WebProxy("http://proxy.company.com:8080") { Credentials = new NetworkCredential("user", "password", "DOMAIN") };
    NetworkSettings.RevocationTimeout = 10000;                  // 10 seconds for an OCSP request or a CRL download
    NetworkSettings.MaxResponseSize = 20L * 1024 * 1024;        // 20 MB: the largest response accepted from a server
    NetworkSettings.BlockPrivateAddresses = true;               // the OCSP and CRL addresses of the certificates cannot point to the internal network

    // The documents received from third parties.
    SecurityLimits.AllowXmlDtd = false;                         // the default: an XML document with a DTD is refused
    SecurityLimits.MaxZipEntries = 1000;                        // ASiC-E containers and Office packages
    SecurityLimits.MaxZipTotalSize = 200L * 1024 * 1024;        // 200 MB: the largest container that the server accepts
    XmlSignatureVerificationPolicy.RejectSha1 = true;           // the XML signatures that use SHA-1 are reported as not valid

    // The certificate cache: the chains, the private keys and the PFX files are kept in memory for 8 hours.
    CertificateCache.MaxAge = TimeSpan.FromHours(8);

    // The revocation cache: no network. Only the data of the provider and the data added below are used.
    string revocationFolder = SampleFile("revocation");
    RevocationCache.UseNetwork = false;
    RevocationCache.Provider = new FolderRevocationProvider(revocationFolder);
    RevocationCache.CrlMaxAge = TimeSpan.FromHours(12);

    // The data can also be added in advance: it is used while it is current, and it is kept until RevocationCache.Clear().
    if (Directory.Exists(revocationFolder))
    {
        foreach (string file in Directory.GetFiles(revocationFolder, "*.crl"))
            RevocationCache.AddCrl(File.ReadAllBytes(file));

        foreach (string file in Directory.GetFiles(revocationFolder, "*.ocsp"))
            RevocationCache.AddOcspResponse(File.ReadAllBytes(file));

        Console.WriteLine("The revocation data of the folder " + revocationFolder + " was added.");
    }
    else
    {
        Console.WriteLine("The folder " + revocationFolder + " does not exist: no revocation data was added.");
    }
}

C# code: revocation data from a folder

The CRLs and the OCSP responses are copied to the folder by an administrator or by a job on a computer with Internet access. The library validates them exactly as downloaded data (issuer, signature, validity).

/// <summary>
/// A source of revocation data for a server without Internet access: the CRLs and the OCSP responses are copied to a folder by an
/// administrator or by a job that runs on a computer with Internet access. The data is validated by the library exactly as the
/// downloaded data (issuer, signature, validity). Return null when the data is not available.
/// </summary>
public class FolderRevocationProvider : IRevocationDataProvider
{
    private readonly string _folder;

    public FolderRevocationProvider(string folder)
    {
        _folder = folder;
    }

    public byte[] GetOcspResponse(X509Certificate2 certificate, X509Certificate2 issuer)
    {
        // An OCSP response saved as <thumbprint of the certificate>.ocsp.
        string file = Path.Combine(_folder, certificate.Thumbprint + ".ocsp");

        return File.Exists(file) ? File.ReadAllBytes(file) : null;
    }

    public byte[] GetCrl(X509Certificate2 certificate, string url)
    {
        // The CRL published at the address written in the certificate (for example http://crl.example.com/ca.crl), saved with the
        // same file name (ca.crl).
        Uri address;
        if (!Uri.TryCreate(url, UriKind.Absolute, out address))
            return null;

        string file = Path.Combine(_folder, Path.GetFileName(address.AbsolutePath));

        return File.Exists(file) ? File.ReadAllBytes(file) : null;
    }
}

C# code: sign without the network

static void SignDocuments(X509Certificate2 certificate)
{
    // Before the first document: the revocation data of the chain of the signing certificate must be available (from the
    // provider or from the added data) for the long-term signatures. A self-signed certificate needs none.
    IReadOnlyList<MissingValidationData> missing = RevocationCache.Prefetch(certificate);
    Console.WriteLine("Certificates without revocation data: " + missing.Count);
    foreach (MissingValidationData item in missing)
        Console.WriteLine("  " + item.Subject + " - " + item.Reason);

    // Several PDF documents with the same certificate: the chain and the private key are reused from the certificate cache.
    for (int index = 1; index <= 3; index++)
    {
        PdfSignature pdfSignature = new PdfSignature(LibrarySerialNumber);
        pdfSignature.LoadPdfDocument(SampleFile("source.pdf"));
        pdfSignature.DigitalSignatureCertificate = certificate;
        pdfSignature.SigningReason = "Document " + index;
        pdfSignature.SignatureStandard = PdfSignatureStandard.Pades;

        File.WriteAllBytes(OutputFile("source[" + index + "].pdf"), pdfSignature.ApplyDigitalSignature());
    }

    CadesSignature cadesSignature = new CadesSignature(LibrarySerialNumber);
    cadesSignature.DigitalSignatureCertificate = certificate;
    cadesSignature.SignatureStandard = CadesSignatureStandard.CadesBes;
    File.WriteAllBytes(OutputFile("test.txt.p7m"), cadesSignature.ApplyDigitalSignature(SampleFile("test.txt")));

    XadesSignature xadesSignature = new XadesSignature(LibrarySerialNumber);
    xadesSignature.DigitalSignatureCertificate = certificate;
    xadesSignature.SignatureStandard = XadesSignatureStandard.XadesB;
    xadesSignature.ApplyDigitalSignature(SampleFile("test.xml"), OutputFile("test[xades].xml"));

    AsicSignature asicSignature = new AsicSignature(LibrarySerialNumber);
    asicSignature.DigitalSignatureCertificate = certificate;
    asicSignature.SignatureStandard = XadesSignatureStandard.XadesB;
    asicSignature.CreateContainer(new[] { SampleFile("test.txt"), SampleFile("source.pdf") }, OutputFile("documents.asice"));

    Console.WriteLine("The documents were signed in the folder " + Path.GetDirectoryName(OutputFile("documents.asice")) + ".");

    // The cache misses since the process started: one chain, one private key and one PFX file for all the documents.
    CertificateCacheStatistics statistics = CertificateCache.Statistics;
    Console.WriteLine("Certificate cache: chains built " + statistics.ChainBuilds + ", private keys opened " + statistics.PrivateKeyOpens
        + ", PFX files loaded " + statistics.PfxLoads);
}

C# code: verify the documents received from third parties

static void VerifyDocuments()
{
    // PDF: the integrity of every signature and the coverage of the last revision of the file.
    PdfSignature pdfSignature = new PdfSignature(LibrarySerialNumber);
    pdfSignature.LoadPdfDocument(OutputFile("source[1].pdf"));
    foreach (PdfSignatureInfo signatureInfo in pdfSignature.DocumentProperties.DigitalSignatures)
    {
        Console.WriteLine("  source[1].pdf: valid " + signatureInfo.SignatureIsValid + ", covers the whole document "
            + signatureInfo.CoversWholeDocument + ", level " + signatureInfo.Level);
    }

    // CAdES.
    CadesVerify cadesVerify = new CadesVerify(File.ReadAllBytes(OutputFile("test.txt.p7m")), LibrarySerialNumber);
    foreach (CadesSignatureInfo signatureInfo in cadesVerify.Signatures)
        Console.WriteLine("  test.txt.p7m: valid " + signatureInfo.SignatureIsValid + ", level " + signatureInfo.Level);

    // XAdES: with RejectSha1 = true, a signature that uses SHA-1 would be reported as not valid.
    foreach (XadesSignatureInfo signatureInfo in new XadesSignature(LibrarySerialNumber).GetSignatures(OutputFile("test[xades].xml")))
        Console.WriteLine("  test[xades].xml: valid " + signatureInfo.SignatureIsValid + ", level " + signatureInfo.Level);

    // ASiC-E: the container is checked against SecurityLimits before it is read (SecurityLimitException).
    AsicSignature asicSignature = new AsicSignature(LibrarySerialNumber);
    Console.WriteLine("  documents.asice: valid " + asicSignature.VerifyDigitalSignature(OutputFile("documents.asice"))
        + ", signed files " + string.Join(", ", asicSignature.GetDataFileNames(OutputFile("documents.asice"))));

    // An XML document with a document type declaration (DTD) is refused: it could load external resources or expand entities.
    string xmlWithDtd = "<?xml version=\"1.0\"?><!DOCTYPE invoice [<!ENTITY company \"Example\">]><invoice>&company;</invoice>";
    try
    {
        using (MemoryStream document = new MemoryStream(Encoding.UTF8.GetBytes(xmlWithDtd)))
            new XadesSignature(LibrarySerialNumber).VerifyDigitalSignature(document);

        Console.WriteLine("  XML document with a DTD: accepted");
    }
    catch (XmlException ex)
    {
        Console.WriteLine("  XML document with a DTD: refused (" + ex.Message + ")");
    }
}

The long-term levels (T, LT, LTA) need a time-stamping server: on an internal network, use a local time-stamping server, such as our on-premise TSA server, and give its address in TimeStamping.ServerUrl. More in the user manual: the revocation cache, the certificate cache, network access and security of the documents that are read.

Run the full sample. The complete Visual Studio project Offline Server, Caches and Network Settings is included in the library download, in the folder NET Sample Projects (.NET 8, .NET 9, .NET 10 and .NET 11) and in NET Framework Sample Projects (.NET Framework 4.6.2), with the test files and a test certificate. Without a serial number the library runs in demo mode. Download the library and the samples · User manual

Frequently asked questions

Can the library sign without Internet access?

Yes. B-B signatures need no network. For the long-term levels, give the revocation data with RevocationCache (AddCrl, AddOcspResponse or an IRevocationDataProvider) and use a time-stamping server of your network.

Are the settings per signature object?

No. NetworkSettings, SecurityLimits, XmlSignatureVerificationPolicy, RevocationCache and CertificateCache are process-wide: set them once, when the application starts. The two caches are thread-safe.

Why is an XML document with a DTD refused?

A document type declaration can load external resources or expand entities (XXE attacks). By default (SecurityLimits.AllowXmlDtd = false) such a document is refused with an XmlException.