Maui - how to use certificate.pfx using X509Certificate2

Dani_S 3,786 Reputation points
2024-01-02T11:45:00.88+00:00

Hi,

I used this code: certificate.pfx located in Resources\Raw folder and also tried on the root of the app.

var cert = new X509Certificate2(@"certificate.pfx", "password");

Exception: System.Security.Cryptography.CryptographicException: 'The system cannot find the file specified.'

How can i fixed it ?

Thanks in advance?

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,934 questions
.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,624 questions
0 comments No comments
{count} votes

Accepted answer
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 76,631 Reputation points Microsoft Vendor
    2024-01-03T02:22:00.06+00:00

    Hello,

    You can use X509Certificate2(Byte[], String) to read the certifcate to byte[] like following code.

    By the way, please make sure this build action of certificate.pfx is MauiAsset

      public async Task<byte[]> ReadCertificateAsByteArray()
       {
           try
           {
               // Get the stream of the certificate from the Assets folder
               using (var stream = await FileSystem.OpenAppPackageFileAsync("certificate.pfx"))
               {
                   if (stream != null)
                   {
                       using (var memoryStream = new MemoryStream())
                       {
                           // Copy the stream to a MemoryStream
                           stream.CopyTo(memoryStream);
    
    
                          // Convert the MemoryStream to byte[]
                           return memoryStream.ToArray();
                       }
                   }
                   else
                   {
                       Console.WriteLine("Certificate file not found in the Assets folder.");
                   }
               }
           }
           catch (Exception ex)
           {
               Console.WriteLine($"Error reading certificate: {ex.Message}");
           }
    
    
          return null;
       }
    

    Then, you can use it in X509Certificate2 like following code.

      var certAsByte = await ReadCertificateAsByteArray();
      var cert = new X509Certificate2(certAsByte, "password");
    

    Best Regards,

    Leon Lu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.