> For the complete documentation index, see [llms.txt](https://docs.apryse.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.apryse.com/xamarin/digital-signature/signature/custom-signing.md).

# Custom Signing in Xamarin

Discover how the Apryse custom signing API simplifies document signing with cryptographic digital signatures. Integrate PDF-specific operations effortlessly with access to HSM tokens, cloud keystores,

The Apryse custom signing API is a set of APIs related to cryptographic digital signatures which allows users to customize the process of signing documents. Among other things, this includes the capability to allow for easy integration of PDF-specific signing-related operations with access to Hardware Security Module (HSM) tokens/devices, access to cloud keystores, access to system keystores, etc. The intent behind this API is to remove the old, tricky, and complicated requirement for users with specific needs to create custom SignatureHandler functor objects.

What follows is a simple code guide to the use of the custom signing API. Please note: any of the steps can be replaced with your own code that provides some custom functionality.

{% tabs %}
{% tab title="C#" %}
{% code lineNumbers="true" %}

```csharp
PDFDoc doc = new PDFDoc(in_docpath);

Page page1 = doc.GetPage(1);

// Create a digital signature field and associated widget.
DigitalSignatureField digsig_field = doc.CreateDigitalSignatureField(in_sig_field_name);
SignatureWidget widgetAnnot = SignatureWidget.Create(doc, new Rect(143, 287, 219, 306), digsig_field);
page1.AnnotPushBack(widgetAnnot);

// Create a digital signature dictionary inside the digital signature field, in preparation for signing.
digsig_field.CreateSigDictForCustomSigning("Adobe.PPKLite",
	in_PAdES_signing_mode? DigitalSignatureField.SubFilterType.e_ETSI_CAdES_detached : DigitalSignatureField.SubFilterType.e_adbe_pkcs7_detached,
	7500); // For security reasons, set the contents size to a value greater than but as close as possible to the size you expect your final signature to be, in bytes.
// ... or, if you want to apply a certification signature, use CreateSigDictForCustomCertification instead.

// (OPTIONAL) Set the signing time in the signature dictionary, if no secure embedded timestamping support is available from your signing provider.
Date current_date = new Date();
current_date.SetCurrentTime();
digsig_field.SetSigDictTimeOfSigning(current_date);

// Save the document incrementally to avoid invalidating any previous signatures.
doc.Save(in_outpath, SDFDoc.SaveOptions.e_incremental);

// Digest the relevant bytes of the document in accordance with ByteRanges surrounding the signature.
byte[] pdf_digest = digsig_field.CalculateDigest(DigestAlgorithm.Type.e_sha256);

X509Certificate signer_cert = new X509Certificate(in_cert_path);

/* Optionally, you can add a custom signed attribute at this point, such as one of the PAdES ESS attributes.
The function we provide takes care of generating the correct PAdES ESS attribute depending on your digest algorithm. */
byte[] pades_versioned_ess_signing_cert_attribute = digsig_field.GenerateESSSigningCertPAdESAttribute(
	signer_cert, DigestAlgorithm.Type.e_sha256);

// Generate the signedAttrs component of CMS, passing any optional custom signedAttrs (e.g. PAdES ESS). The signedAttrs are certain attributes that become protected by their inclusion in the signature.
byte[] signedAttrs = DigitalSignatureField.GenerateCMSSignedAttributes(pdf_digest, 
	pades_versioned_ess_signing_cert_attribute);

// Calculate the digest of the signedAttrs (i.e. not the PDF digest, this time).
byte[] signedAttrs_digest = DigestAlgorithm.CalculateDigest(DigestAlgorithm.Type.e_sha256, signedAttrs);
```

{% endcode %}
{% endtab %}
{% endtabs %}

At this point, use your signing provider (e.g. HSM device, cloud keystore) to sign the digest of signedAttrs. Your input should be the variable signedAttrs\_digest. In the following code, we assume the output is in a variable named signature\_value.

{% tabs %}
{% tab title="C#" %}
{% code lineNumbers="true" %}

```csharp
// Then, load all your chain certificates into a container of X509Certificate.
X509Certificate[] chain_certs = {};

// Then, create ObjectIdentifiers for the algorithms you have used.
ObjectIdentifier digest_algorithm_oid = new ObjectIdentifier(DigestAlgorithm.Type.e_sha256);
ObjectIdentifier signature_algorithm_oid = new ObjectIdentifier(ObjectIdentifier.Predefined.e_RSA_encryption_PKCS1);

// Then, put the CMS signature components together.
byte[] cms_signature = DigitalSignatureField.GenerateCMSSignature(
	signer_cert, chain_certs, digest_algorithm_oid, signature_algorithm_oid,
	signature_value, signedAttrs);

// Write the signature to the document.
doc.SaveCustomSignature(cms_signature, digsig_field, in_outpath);
```

{% endcode %}
{% endtab %}
{% endtabs %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.apryse.com/xamarin/digital-signature/signature/custom-signing.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
