Digital Signatures |
Sign(String, String, String, String, String, String, String, String, Int32, RectangleF, TimeStampAuthority) adds a digital signature to an existing PDF document. The signature proves who signed the document and that it was not changed after it was signed. PDF viewers show it in their signatures panel, with the signer, the reason, the location and the contact information you give. ValidateSignatures(String) checks the signatures of a document.
Signing and validation are done in managed code, on Windows, Linux and macOS. To sign a document while you create it with the document model, see Digital Signature Element.
The document is signed with a certificate and its private key from a PKCS#12 file (.pfx or .p12), opened with the password of the file, or with a key held outside the application (see Keys held outside the application). For documents that other people must trust, use a certificate issued for you by a certification authority. For tests you can make a self-signed certificate, for example with OpenSSL on any platform:
openssl req -x509 -newkey rsa:2048 -nodes -days 365 -subj "/CN=Test Signer"
-keyout key.pem -out cert.pem
openssl pkcs12 -export -inkey key.pem -in cert.pem -out test-signer.pfx
-passout pass:passwordEach command is one line; it is wrapped here to fit the page.
PDF viewers show the signatures made with a self-signed certificate as valid (the document was not changed) but the signer as not trusted.
The signature is placed in a box on one page: the page index starts at 0, and the box is given in points (1/72 inch) from the top left corner of the page; an empty rectangle makes an invisible signature. The methods sign from a file to a file, from a stream to a stream, and from a byte array to a byte array. The last argument is a time stamp authority, or null.
using ExpertPdf.Anywhere.Drawing; using ExpertPdf.Anywhere.PDFSecurity; PdfSecurityManager securityManager = new PdfSecurityManager(); // the bottom right of the first page of an A4 document RectangleF bounds = new RectangleF(345, 700, 200, 60); // file to file securityManager.Sign("report.pdf", "signed-report.pdf", "signer.pfx", "certificate password", "Approval", "I approve this report", "Head office", "signer@example.com", 0, bounds, null); // memory to memory byte[] signedBytes = securityManager.Sign(File.ReadAllBytes("invoice.pdf"), "signer.pfx", "certificate password", "Issuer", "Invoice issued", "Head office", "billing@example.com", 0, bounds, null);
A document can carry several signatures: sign the signed document again, each time in a save of its own. The earlier signatures stay valid.
DigestAlgorithm - the hash algorithm of the signature: SHA-256 (the default), SHA-384 or SHA-512.
SignatureBackgroundImage - the bytes of a PNG, JPEG, GIF, BMP or WebP image (a company logo, a seal, a scanned handwritten signature) drawn behind the text of a visible signature, fitted in the box with its aspect ratio kept. SignatureBackgroundOpacity sets how strongly it is drawn, from 0 to 1 (0.25 by default). The image is lightened, not made transparent, so the appearance is allowed in PDF/A and PDF/X documents.
EnableLtv - makes the signature LTV-enabled (long-term validation): the revocation data of the signing certificate and of its issuers (an OCSP response or a certificate revocation list for each) is obtained from the addresses the certificates name and embedded in the signed document with the issuer certificates. The signature can then be validated after the certificates expire, or once the issuer's services can no longer be reached, without going online. Signing fails with a SecurePdfException when a certificate of the chain names no revocation service or none can be reached; a self-signed root needs no revocation data.
PdfSecurityManager securityManager = new PdfSecurityManager(); securityManager.DigestAlgorithm = SignatureDigest.SHA384; securityManager.SignatureBackgroundImage = File.ReadAllBytes("logo.png"); securityManager.SignatureBackgroundOpacity = 0.25f; securityManager.EnableLtv = true; securityManager.Sign("report.pdf", "signed-report.pdf", "signer.pfx", "certificate password", "Approval", "I approve this report", "Head office", "signer@example.com", 0, new RectangleF(320, 36, 240, 70), null);
Set SourcePdfPassword to the user or the owner password of a protected document. The signed document keeps its protection. When a document must be both protected and signed, protect it first and sign it after: a change made after signing invalidates the signature.
PdfSecurityManager securityManager = new PdfSecurityManager(); securityManager.SourcePdfPassword = "owner"; using (FileStream source = File.OpenRead("secured.pdf")) using (FileStream destination = File.Create("secured-signed.pdf")) { securityManager.Sign(source, destination, "signer.pfx", "certificate password", "Approval", "Approved for distribution", "Head office", "signer@example.com", 0, new RectangleF(345, 700, 200, 60), null); }
Without a time stamp, the signing time comes from the clock of the computer that signed. A TimeStampAuthority adds a time stamp from a time stamp server (RFC 3161), which proves when the document was signed. Give the address of the server, and a user name and a password when the server requires them. Signing then needs a connection to the server.
TimeStampAuthority tsa = new TimeStampAuthority(new Uri("https://your-tsa-server/")); // tsa.UserName = "user"; // tsa.Password = "password"; new PdfSecurityManager().Sign("report.pdf", "signed-report.pdf", "signer.pfx", "certificate password", "Approval", "I approve this report", "Head office", "signer@example.com", 0, new RectangleF(345, 700, 200, 60), tsa);
A certification (author) signature also states the changes allowed after it. Set CertificationLevel before calling Sign: NoChangesAllowed, FormFillingAllowed (form filling and signing) or FormFillingAndAnnotationsAllowed. The default, None, makes an ordinary approval signature.
A document has at most one certification signature and it must be its first signature: certifying a signed document throws an exception, and so does signing a document certified with no changes allowed. When other people sign the document after it was certified, add their empty signature fields first with AddSignatureField(String, String, String, Int32, RectangleF): signing an existing field is form filling, which the certification allows, while some validators report a signature field added after the certification as a change it does not allow. A Sign call with the name of an empty field signs that field, at its position.
PdfSecurityManager securityManager = new PdfSecurityManager(); // 1. the empty field of the approver, on the first page securityManager.AddSignatureField("report.pdf", "report-field.pdf", "Approval", 0, new RectangleF(40, 700, 200, 60)); // 2. the author certifies the document: form filling and signing remain allowed PdfSecurityManager author = new PdfSecurityManager(); author.CertificationLevel = PdfCertificationLevel.FormFillingAllowed; author.Sign("report-field.pdf", "certified.pdf", "author.pfx", "certificate password", "Author", "I am the author of this report", "Head office", "author@example.com", 0, new RectangleF(345, 700, 200, 60), null); // 3. the approver signs the empty field (its position comes from the field) new PdfSecurityManager().Sign("certified.pdf", "approved.pdf", "approver.pfx", "certificate password", "Approval", "Approved", "Branch office", "approver@example.com", 0, RectangleF.Empty, null);
The Sign overloads that take an IExternalSigner instead of a certificate file sign with a key that never leaves its device or service - a hardware security module, a smart card or a USB token, a cloud key service. The library builds the whole signature and asks the signer for one value: the signature of an ExternalSigningRequest with the private key of the first of its Certificates. The value is checked against the certificate before it is written. The digest, the certification level, the background image, long-term validation and time stamps work as with a certificate file. Two signers are ready to use:
CertificateStoreSigner - a certificate of the system certificate store, found by its thumbprint (in the current user's store, then the local machine's), with its key in the store or on a token whose middleware the store reaches.
Pkcs11Signer - a key on a PKCS#11 device, through the vendor's PKCS#11 library, on Windows, Linux and macOS.
Both are disposable and keep the certificate or the token session open until they are disposed.
// a certificate of the system store, by its thumbprint using (CertificateStoreSigner signer = new CertificateStoreSigner("3F8A...C2")) { new PdfSecurityManager().Sign("report.pdf", "signed-report.pdf", signer, "Signature1", "Approved", "Head office", "signer@example.com", 0, new RectangleF(345, 700, 200, 60), null); } // a key on a PKCS#11 token: the vendor's library and the PIN using (Pkcs11Signer signer = new Pkcs11Signer("/usr/lib/softhsm/libsofthsm2.so", "1234", null, null)) { new PdfSecurityManager().Sign("report.pdf", "token-signed.pdf", signer, "Signature1", "Approved", "Head office", "signer@example.com", 0, new RectangleF(345, 700, 200, 60), null); }
For another key service implement the interface. For an RSA key the value is a PKCS#1 v1.5 signature of Digest, the hash of Data computed with DigestAlgorithm; for an ECDSA key the DER-encoded signature, or r and s concatenated. The certificates are DER-encoded: the signing certificate first, then its issuers. This signer uses an RSA key the application can reach:
using System.Collections.Generic; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using ExpertPdf.Anywhere.PDFSecurity; class RsaKeySigner : IExternalSigner { private readonly X509Certificate2 certificate; public RsaKeySigner(X509Certificate2 certificate) { this.certificate = certificate; } public IList<byte[]> Certificates { get { return new List<byte[]> { certificate.RawData }; } } public byte[] Sign(ExternalSigningRequest request) { HashAlgorithmName hash = HashAlgorithmName.SHA256; if (request.DigestAlgorithm == SignatureDigest.SHA512) hash = HashAlgorithmName.SHA512; else if (request.DigestAlgorithm == SignatureDigest.SHA384) hash = HashAlgorithmName.SHA384; using (RSA rsa = certificate.GetRSAPrivateKey()) { return rsa.SignHash(request.Digest, hash, RSASignaturePadding.Pkcs1); } } }
When the signature value cannot be produced during the call - a remote signing service where the signer approves on another device, or a smart card in a user's browser - sign in two steps. PrepareExternalSignature(String, String, IListByte, String, String, String, String, Int32, RectangleF) writes the document with a reserved signature and returns the request to be signed; CompleteExternalSignature(String, String, String, IListByte, SignatureDigest, Byte) writes the signature value into it, with the same certificates and digest. The two steps can run in different processes; long-term validation and time stamps are not available in this mode.
ValidateSignatures(String) checks every signature of a document and returns a SignatureValidationResult for each: the field name, the signer, the signing time, the reason, location and contact information, the digest and signature algorithms, whether the document was changed after signing in a way the signature does not allow (IsDocumentModified), whether the certificate was valid at the signing time and its chain ends in a trusted root certificate, the time stamp, whether the signature is LTV-enabled (IsLtvEnabled), the revocation status, the certification level, and the overall Status: Valid, Unknown (the document is intact but the signer could not be verified, for example a self-signed certificate) or Invalid. Messages explains a status that is not Valid. A password protected document is opened with SourcePdfPassword.
SignatureValidationOptions adds root certificates to trust (your own certification authority, or a test certificate), can limit the trust to them (UseSystemTrustStore), and turns on the online revocation check (CheckRevocation, off by default), which asks the revocation lists and OCSP servers named in the certificates. The operating system checks the revocation of a certificate chain that ends in a root certificate the computer trusts; for a chain trusted only through TrustedRootCertificates the revocation status of a certificate that is not revoked is reported as Unknown.
SignatureValidationOptions options = new SignatureValidationOptions(); options.CheckRevocation = true; // options.TrustedRootCertificates.Add(new X509Certificate2("our-root-ca.cer")); PdfSecurityManager securityManager = new PdfSecurityManager(); foreach (SignatureValidationResult result in securityManager.ValidateSignatures( "approved.pdf", options)) { Console.WriteLine("{0}: {1}, signed by {2} on {3}", result.FieldName, result.Status, result.SignerName, result.SigningTime); Console.WriteLine(" changed: {0}, trusted: {1}, time stamp: {2}, LTV: {3}", result.IsDocumentModified, result.IsCertificateChainTrusted, result.HasTimeStamp, result.IsLtvEnabled); foreach (string message in result.Messages) Console.WriteLine(" " + message); }
A signature followed by later changes (another signature, for example) does not cover the whole file (CoversWholeDocument is false); IsDocumentModified tells whether those changes are allowed.
The PdfDigitalSignature console sample (C# and VB.NET, for Windows, Linux and macOS) signs the documents that come with it from a file, from memory and, protected with a password, from a stream. It uses certificate.pfx, a self-signed test certificate (password: expertpdf). Run it with /tsa:server_url to add time stamps. It also certifies a document with an empty field that an approver signs, and validates all the signatures. The SignAndValidate page of the web sample signs a form with a chosen digest and a background image and shows the validation report.