# Digital Signature

The PdfViewer enables you to display, sign, and verify documents within your application, and make sure that the documents have not been modified.

## What is a Digital Signature?

The digital signature is the equivalent of the hand-written signature and is intended to solve security problems in the digital communication. The signature is unique to each signer and is widely used to confirm that the document content originated from the signer and has not been modified in any way.

The digital signatures rely on a mathematical algorithm, which generates a public and a private key. The private key is used to create the signature while the user signs the document. The algorithm creates a hash (`#`) over the document data and uses the signer's private key to encrypt this hash. The result of this operation is the digital signature of the document. Once the document is signed, any change on it invalidates the hash, respectively the signature is invalidated.

## Cryptography Standards

The PdfViewer allows you to validate signature fields by using the following standard Cryptography Standards:

* `adbe.x509.rsa_sha1` ([PKCS #1](https://tools.ietf.org/html/rfc8017))

* `adbe.pkcs7.sha1` ([PKCS #7](https://tools.ietf.org/html/rfc2315))

* `adbe.pkcs7.detached` (PKCS #7 Detached)

## Signature Field

The information about a digital signature in a document is stored in a signature field, which can be obtained through the `AcroForm` property of the document. This field exposes a property called `Signature`, which is responsible for the validation.

> The only possible approach to add signature fields and widgets to PDF files which do not have any fields, is to use the [RadPdfProcessing](https://docs.telerik.com/devtools/document-processing/libraries/radpdfprocessing/overview) library. With it, you can [import the existing PDF](https://docs.telerik.com/devtools/document-processing/libraries/radpdfprocessing/formats-and-conversion/pdf/pdfformatprovider/pdfformatprovider#import), modify its [AcroForm `FormFieldCollection`](https://docs.telerik.com/devtools/document-processing/libraries/radpdfprocessing/model/interactive-forms/formfieldcollection), [create and position widgets](https://docs.telerik.com/devtools/document-processing/libraries/radpdfprocessing/model/interactive-forms/widgets#widget-class) for the new fields, and [export the result to the PDF](https://docs.telerik.com/devtools/document-processing/libraries/radpdfprocessing/formats-and-conversion/pdf/pdfformatprovider/pdfformatprovider#export) `FileStream` or `MemoryStream`. The exported file can then be [imported in RadPdfViewer](https://docs.telerik.com/devtools/wpf/controls/radpdfviewer/showing-a-file#setting-the-document-in-code-behind), so that you can render the resultant document.

For sample code for creating fields and widgets with the RadPdfProcessing library, refer to the [CreateInteractiveForms SDK example](https://github.com/telerik/document-processing-sdk/tree/master/PdfProcessing/CreateInteractiveForms).

## Dependencies

To use the signature API of the PdfViewer, users have to add a reference to the `System.Security.Cryptography.Pkcs` NuGet package version 9.0.9 or later.

## Signing

You can apply a signature through the `SignSignatureDialog` when a document with a signature field is loaded in the PdfViewer. This dialog enables you to choose a `.pfx` file representing the certificate and enter the password for it. Clicking the **Sign** button prompts you to save the signed document to a new file. The newly saved file then opens in the PdfViewer.

To use the `SignSignatureDialog`, first register it through the `ExtensibilityManager`.

#### **Register the SignSignatureDialog by using the ExtensibilityManager**

```C#
ExtensibilityManager.RegisterSignSignatureDialog(new SignSignatureDialog());
```

To add the dialog through XAML, use the `RegisterSignSignatureDialog` property of the `RadPdfViewerAttachedComponents` class.

#### **Register the SignSignatureDialog through XAML**

```XAML
<telerik:RadPdfViewer telerik:RadPdfViewerAttachedComponents.RegisterSignSignatureDialog="True" />
```

When registered, the `SignSignatureDialog` can be shown by invoking the `ShowSignSignatureDialogCommand`. The following example shows how to access this command, instantiate some context, which points to the first signature field in the document, and invoke this command.

#### **Show the SignSignatureDialog from code-behind**

```C#
ShowSignSignatureDialogCommandContext context = new ShowSignSignatureDialogCommandContext();
SignatureField firstSignatureField = this.pdfViewer.Document.AcroForm.FormFields.FirstOrDefault(field => field.FieldType == FormFieldType.Signature) as SignatureField;

if (firstSignatureField != null && firstSignatureField.Signature == null)
{
	context.SignatureField = firstSignatureField;
}

this.pdfViewer.CommandDescriptors.ShowSignSignatureDialogCommandDescriptor.Command.Execute(context);
```

**The SignSignatureDialog in the PdfViewer**

![WinUI RadPdfViewer Sign Signature Dialog in RadPdfViewer](https://www.telerik.com/winui/documentation/assets/9249b7d54e1b5e1f23dabf4bf82db678/radpdfviewer-digital-signature-0.png)

## Validation

In the PDF document model, validation is performed per signature. A signed document is considered valid when  it has not been changed after the signing and all of its certificates have a valid trusted root certificate.

### Using the SignaturePropertiesDialog

The `SignaturePropertiesDialog` provides detailed information on which signature is invalid and why.

To use this dialog, register it first through the `ExtensibilityManager`.

#### **Register the SignaturePropertiesDialog**

```C#
ExtensibilityManager.RegisterSignaturePropertiesDialog(new SignaturePropertiesDialog());
```

To add the dialog through XAML, use the `RegisterSignaturePropertiesDialog` property of the `RadPdfViewerAttachedComponents` class.

#### **Register the SignaturePropertiesDialog through XAML**

```XAML
<telerik:RadPdfViewer telerik:RadPdfViewerAttachedComponents.RegisterSignaturePropertiesDialog="True" />
```

When registered, the `SignaturePropertiesDialog` can be shown by invoking the `ShowSignaturePropertiesDialogCommand`. The following example shows how to access this command, instantiate some context, which points to the first signature field in the document, and invoke this command.

#### **Show the SignaturePropertiesDialog from code-behind**

```C#
ShowSignaturePropertiesDialogCommandContext context = new ShowSignaturePropertiesDialogCommandContext();
SignatureField firstSignatureField = this.pdfViewer.Document.AcroForm.FormFields.FirstOrDefault(field => field.FieldType == FormFieldType.Signature) as SignatureField;

if (firstSignatureField != null && firstSignatureField.Signature != null)
{
	context.SignatureField = firstSignatureField;
	context.SignatureValidationProperties = this.pdfViewer.SignatureValidationProperties;
}

this.pdfViewer.CommandDescriptors.ShowSignaturePropertiesDialogCommandDescriptor.Command.Execute(context);
```

The following figure shows how the `SignaturePropertiesDialog` looks like when visualizing a signature whose validation result is `Unknown`.

**The SignaturePropertiesDialog in the PdfViewer**

![WinUI RadPdfViewer Signature Properties Dialog in RadPdfViewer](https://www.telerik.com/winui/documentation/assets/0262569ddcc961b456abb7faf728c5eb/radpdfviewer-digital-signature-1.png)

### Validating Signatures in Code-Behind

The `Signature` class exposes the following methods for signature validation:

* `Validate`—Accepts a parameter of type `SignatureValidationProperties` which it uses while validating the signature. The `SignatureValidationProperties` class exposes the following properties:
  * `Chain`—Gets or sets the chain used to validate the certificate that signed the digital signature. It is of type [X509Chain](https://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509chain\(v=vs.110\).aspx).
  * `ChainStatusFlags`—Gets or sets the chain status flags which describes the used signature certificate as invalid. It is of type [X509ChainStatusFlags](https://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509chainstatusflags\(v=vs.110\).aspx).
  `Validate()` returns object of type `SignatureValidationResult`.

* `TryValidate`—Returns a boolean value indicating whether the validation succeeded or not.

  The method provides two overloads. The first one accepts an `out` parameter containing a `SignatureValidationResult` object. The second one allows you to also pass `SignatureValidationProperties`.

> The `Validate` method throws an exception if a problem with the signature occurs, while `TryValidate` returns `false` in this case.

#### **Validate a field**

```C#
string validationStatus;

// For simplicity, the example handles only the first signature.
SignatureField firstSignatureField = this.pdfViewer.Document.AcroForm.FormFields.FirstOrDefault(field => field.FieldType == FormFieldType.Signature) as SignatureField;
if (firstSignatureField != null && firstSignatureField.Signature != null)
{
	SignatureValidationResult validationResult;
	if (firstSignatureField.Signature.TryValidate(out validationResult))
	{
		if (!validationResult.IsDocumentModified)
		{
			if (validationResult.IsCertificateValid)
			{
				validationStatus = "Valid";
			}
			else
			{
				validationStatus = "Unknown";
			}
		}
		else
		{
			validationStatus = "Invalid";
		}
	}
	else
	{
		validationStatus = "Invalid";
	}
}
else
{
	validationStatus = "None";
}
```

## Limitations

The usage of digital signatures in the PdfViewer comes with the following limitations:

* The validation of a signature depends on the bytes representing the document. Thus, to validate a signature, the stream used to import the document must be still open.

* The validation is always performed for the current field, against the state of the document in the moment of importing.

## See Also

* [Opening Files](https://www.telerik.com/winui/documentation/controls/radpdfviewer/file-operations/open-files)
