How to Sign and Verify a File with a Certificate in Azure Key Vault In C#

I am attempting to write a tool to sign and verify files with a certificate in Azure Key Vault. Previously, our tool kicked off SignTool.exe as a process. I’d like the new tool to work properly in code.

I have found a lot of examples of how to get an X509 certificate from Azure and use it to sign and then verify the data.

What I can’t work out is how I embed the signature in the file and how I verify the file itself.

I’ve googled this for hours. All examples in code don’t use files. All file examples use either SignTool.exe or AzureSignTool.exe. I’m just missing the last piece in the puzzle.

Any help appreciated. My current code is below. It’s geared to Azure Key Vault but I believe the scenario works with any X509 certificate.

namespace Test.Signing.Shell;

public static class Program
{
    #region Public interface

    public static int Main()
    {
        try
        {
            var keyVaultUri = new Uri("KEY_VAULT_URI");
            var tenantId = "TENANT_ID";
            var clientId = "CLIENT_ID";
            var clientSecret = "CLIENT_SECRET";
            var certificateName = "CERTIFICATE_NAME";

            var filePath = @"FILE_PATH";

            var signer = new Signer(keyVaultUri, tenantId, clientId, clientSecret, certificateName);

            signer.SignFile(filePath);

            Console.WriteLine("Sign process complete");

            return 0;
        }
        catch (Exception e)
        {
            Console.WriteLine($"Sign process failed: {e}");

            return 1;
        }
    }

    #endregion
}
    

using System.Net.Sockets;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
using Microsoft.Identity.Client;

namespace Test.Signing
{
    public class Signer
    {
        public Signer(Uri keyVaultUri, string tenantId, string clientId, string clientSecret, string certificateName)
        {
            KeyVaultUri = keyVaultUri;
            TenantId = tenantId;
            ClientId = clientId;
            ClientSecret = clientSecret;
            CertificateName = certificateName;
        }

        private Uri KeyVaultUri { get; }

        private string TenantId { get; }

        private string ClientId { get; }

        private string ClientSecret { get; }

        private string CertificateName { get; }

        public void SignFile(string filePath)
        {
            var client = GetSecretClient();

            var certificateSecret = GetCertificateSecret(client);

            var certificate = GetCertificate(certificateSecret);

            SignFile(certificate, filePath);
        }

        private SecretClient GetSecretClient()
        {
            SecretClient secretClient;

            try
            {
                var credential = new ClientSecretCredential(TenantId, ClientId, ClientSecret);

                Console.WriteLine("Connecting to the key vault...");

                secretClient = new SecretClient(KeyVaultUri, credential);
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to connect to the key vault", ex);
            }

            return secretClient;
        }

        private KeyVaultSecret GetCertificateSecret(SecretClient secretClient)
        {
            KeyVaultSecret secret;

            try
            {
                Console.WriteLine("Retrieving the certificate secret...");

                secret = secretClient.GetSecret(CertificateName);
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to retrieve the certificate from the key vault", ex);
            }

            return secret;
        }

        private X509Certificate2 GetCertificate(KeyVaultSecret secret)
        {
            X509Certificate2 certificate;

            try
            {
                Console.WriteLine("Creating the certificate from the secret...");

                var certificateBytes = Convert.FromBase64String(secret.Value);

                 certificate = new X509Certificate2(certificateBytes);
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to create the certificate from the secret", ex);
            }

            return certificate;
        }

        private void SignFile(X509Certificate2 certificate, string filePath)
        {
            try
            {
                using (var rsa = certificate.GetRSAPrivateKey())
                {
                    using (var fileStream = File.OpenRead(filePath))

                    using (var hashAlgorithm = SHA256.Create())
                    {
                        var hash = hashAlgorithm.ComputeHash(fileStream);

                        var signature = rsa.SignHash(hash, HashAlgorithmName.SHA256, RSASignaturePadding.Pss);

                        var signatureIsValid = rsa.VerifyHash(hash, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pss);
                        
                        // QUESTION:  HOW DO I ADJUST THIS CODE TO PUT THE SIGNATURE IN THE FILE AND THEN TO VERIFY THE FILE?

                        if (signatureIsValid)
                            Console.WriteLine("Signature is valid");
                        else
                            Console.WriteLine("Signature is not valid");
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to sign file", ex);
            }
        }
    }
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật