Spire.PDF is a professional PDF library applied to creating, writing, editing, handling and reading PDF files without any external dependencies. Get free and professional technical support for Spire.PDF for .NET, Java, Android, C++, Python.

Sun Sep 17, 2023 8:54 am

Hi there,

I would like to digitally sign my PDF document with an Azure KeyVault HSM. For this I cannot export the certificate (including private key) to sign the PDF on my own computer (because no URL can be shared, search for Keyvault in this forum and there is 1 post). Instead, I sent a digest to Keyvault which is then digitally signed. However I can't find the way to incorporate this using spire.pdf. Another program uses a similar approach but I cant find the Spire.PDF way of doing this (because no URL can be shared, search for DevExpress "how-to-use-azure-key-vault-api-to-sign-a-document"). How can I achieve this?

Regards,
Duco

duco.vdas
 
Posts: 4
Joined: Wed Nov 09, 2016 9:13 pm

Mon Sep 18, 2023 5:51 am

Hi,

Thanks for your feedback.
Below is an example code snippet that you can use to test the functionality:
Code: Select all
static void Main(string[] args)
{
    PdfDocument document = new PdfDocument(@"in.pdf");
    var certificate = FindEpsitecCertificate();
    var pdfCert = new Spire.Pdf.Security.PdfCertificate(certificate);
    var pdfSignature = new Spire.Pdf.Security.PdfSignature(document, document.Pages[0], pdfCert, "Epsitec SA")
    {
        DateLabel = "Date:",
        Date = DateTime.Now,
        DocumentPermissions = Spire.Pdf.Security.PdfCertificationFlags.AllowFormFill | Spire.Pdf.Security.PdfCertificationFlags.ForbidChanges,
        ContactInfo = "...",
        Certificated = true,
        LocationInfo = "...",
        Reason = "..."
    };
    document.FileInfo.IncrementalUpdate = false;
    document.CompressionLevel = Spire.Pdf.PdfCompressionLevel.Best;
    document.SaveToFile(@"result.pdf");
}



static X509Certificate2 FindEpsitecCertificate()
{
var store = new X509Store(StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly)
return store.Certificates[0];
}

//static X509Certificate2 FindEpsitecCertificate()
//{
// X509Store store = new X509Store(StoreLocation.CurrentUser);
// store.Open(OpenFlags.ReadOnly);

// var sel = X509Certificate2UI.SelectFromCollection(store.Certificates, null, null, X509SelectionFlag.SingleSelection);

// return sel[0];
//}


Please find the attached class files that you can utilize with the provided code. Feel free to modify the code as per your specific requirements.

If you encounter any issues or have further questions, please don't hesitate to ask. We are here to assist you.

Best regards,
Triste
E-iceblue support team
User avatar

Triste.Dai
 
Posts: 1000
Joined: Tue Nov 15, 2022 3:59 am

Mon Sep 18, 2023 1:00 pm

Hi Triste,

In your example a certificate is imported from the localmachine/user certificate store. However, I don't need the certificate, because this is stored safely in the HSM. I want the HSM to sign the PDF file as descriped in the DevExpress article that I mentioned earlier. For this a digest is calculated from the PDF document, which is then signed by the HSM. The resulting signature, must then be included in the Spire.pdf document using (i think) the PdfSignature class.

Regards,
Duco

duco.vdas
 
Posts: 4
Joined: Wed Nov 09, 2016 9:13 pm

Tue Sep 19, 2023 9:31 am

Hi Duco,

Thanks for your feedback.
While we are not familiar with Azure Key Vault HSM, we think that the process of using Azure Key Vault HSM for document signing is similar to utilizing USB Tokens for the same purpose. Please refer to the following code, the code locates a certificate file based on its fingerprint and then utilizes the private key stored in a USB Token to sign the hash value of the document.
Code: Select all
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(@"sample.pdf");
X509Store store = new X509Store(StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindByThumbprint, "f9b500ad95cda70cd5157c3a1df8c35049c3bef0", false);
X509Certificate2 cert = new X509Certificate2(certs[0]);

//create CustomPKCS7SignatureFormatterWithAPI
BugDebug.CustomPKCS7SignatureFormatterWithAPI customPKCS7SignatureFormatter = new BugDebug.CustomPKCS7SignatureFormatterWithAPI(cert);
PdfSignature signature = new PdfSignature(document: doc, page: doc.Pages[0], customPKCS7SignatureFormatter, signatureName: "test")
{
    Bounds = new RectangleF(location: new PointF(x: 74, y: 635), size: new SizeF(width: 90, height: 158)),
};
signature.Certificated = true;
signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill | PdfCertificationFlags.ForbidChanges;
doc.SaveToFile(@"out.pdf", Spire.Pdf.FileFormat.PDF);
doc.Close();

While our familiarity with Azure Key Vault HSM is limited, we will do our best to provide guidance and support.

Best regards,
Triste
E-iceblue support team
User avatar

Triste.Dai
 
Posts: 1000
Joined: Tue Nov 15, 2022 3:59 am

Wed Oct 04, 2023 8:57 am

Hi Triste,

Thanks for the example. I've now adjusted my functions to incoporate the PdfSignatureFormatter. It is now possible to add the cryptography client from KeyVault such that I can Sign using KeyVault. However when I open the signed document I get an error message. Can you see why I received an error message? I've attached my code and the document with error message.

Kind regards,
Duco

duco.vdas
 
Posts: 4
Joined: Wed Nov 09, 2016 9:13 pm

Fri Oct 06, 2023 7:11 am

Hi Duco,

Thanks for your feedback.
I will investigate this matter and get back to you with a solution or update on the progress as soon as possible.

Best regards,
Triste
E-iceblue support team
User avatar

Triste.Dai
 
Posts: 1000
Joined: Tue Nov 15, 2022 3:59 am

Sat Oct 07, 2023 8:55 am

Hi,

Thank you for your inquiry. I have consulted with our developers and they have informed me that the issue is due to a discrepancy between the length of the data being signed and the length of the pre obtained signature.

To resolve this issue, you will need to modify the code in the GetSignatureLength() method to ensure that it returns the same length of the signature generated by the Sign(Byte[] content) method.

Here is an example of how you can modify the code:

Code: Select all
private uint GetSignatureLength()
        {
            // NOTE: We just have to pass in the method any string, it doesn't
            // matter which exactly.
            string text = Environment.CurrentDirectory;

            byte[] data = System.Text.Encoding.UTF8.GetBytes(text);

            SignResult rsaSignResult = m_cryptoClient.SignData(SignatureAlgorithm.RS256, data);
            var signatureAzure = rsaSignResult.Signature;
            return signatureAzure.Length;

        }

Please note that if you know the expected signature length in advance, you can simply set the signatureLength variable to that fixed value in the Parameters.Add("SignatureLength", signatureLength); line of code.

Thank you for your understanding and cooperation. If you have any further questions or concerns, please feel free to let us know.

Best regards,
Triste
E-iceblue support team
User avatar

Triste.Dai
 
Posts: 1000
Joined: Tue Nov 15, 2022 3:59 am

Mon Oct 09, 2023 6:03 am

Hi Triste,

Thanks for the reply, the signed PDF now opens. Unfortunately it says the signature is invalid because of an ASN-1 parse error? See the attached screenshot and PDF. Can you please help with this?

duco.vdas
 
Posts: 4
Joined: Wed Nov 09, 2016 9:13 pm

Mon Oct 09, 2023 9:04 am

Hi,

Thanks for your feedback.
I have reported this issue to our dev team, they will investigate and work out a solution for you. Once there are any updates available, I will inform you asap.

Best regards,
Triste
E-iceblue support team
User avatar

Triste.Dai
 
Posts: 1000
Joined: Tue Nov 15, 2022 3:59 am

Tue Mar 11, 2025 4:57 pm

Hi E-iceblue support team,

We are testing Digitally sign using Azure Keyvault HSM is the same in this topic, could you update status for this issue?
Please update to us the status and examples if your dev team processed this issue.

msigvnit
 
Posts: 4
Joined: Fri Jul 22, 2022 6:05 am

Wed Mar 12, 2025 1:36 am

Hello,

Thank you for your attention.
Sorry, we have not made any breakthrough progress on this issue yet. We will further investigate the solution and I will inform you as soon as there is any good news.

Sincerely,
William
E-iceblue support team
User avatar

William.Zhang
 
Posts: 732
Joined: Mon Dec 27, 2021 2:23 am

Return to Spire.PDF