PDF Digital Signature with an Azure Key Vault Certificate in C#

void DigitallySignPDFFile(string unsignedDocument, string signedDocument)
{
    PdfSignature ps = new PdfSignature("");

    //load the PDF document
    ps.LoadPdfDocument(unsignedDocument);

    //set the hash algorithm
    ps.HashAlgorithm = SignLib.HashAlgorithm.SHA256;

    //Digital signature certificate will be loaded from Azure Key Vault
    string keyVaultUrl = "https://YOUR-KEYVAULT-NAME.vault.azure.net/";
    string vaultCertificateName = "NAME-OF-THE-CERTIFICATE";

    //get the PFX digital certificate from Key Vault
    var client = new SecretClient(new Uri(keyVaultUrl), new DefaultAzureCredential());

    //the digital certificate is downloaded as PFX without password
    KeyVaultSecret secret = client.GetSecret(vaultCertificateName);

    //the certificate is converted from BASE64
    byte[] azureCert = Convert.FromBase64String(secret.Value);

    //Load the signature certificate from byte array. The PFX password is empty
    ps.DigitalSignatureCertificate = DigitalCertificate.LoadCertificate(azureCert, "");

    //write the signed file
    File.WriteAllBytes(signedDocument, ps.ApplyDigitalSignature());
}

See also: