Skip to content

Commit

Permalink
PFX: use newer loader api on net9+
Browse files Browse the repository at this point in the history
  • Loading branch information
webprofusion-chrisc committed Nov 1, 2024
1 parent 5146b4e commit 6cfcb0a
Showing 1 changed file with 27 additions and 2 deletions.
29 changes: 27 additions & 2 deletions src/Certify.Shared/Management/CertificateManager.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
Expand Down Expand Up @@ -372,7 +372,24 @@ public static async Task<X509Certificate2> StoreCertificate(
{
// https://support.microsoft.com/en-gb/help/950090/installing-a-pfx-file-using-x509certificate-from-a-standard--net-appli
X509Certificate2 certificate;

#if NET9_0_OR_GREATER
try
{
var pfxBytes = File.ReadAllBytes(pfxFile);
certificate = X509CertificateLoader.LoadPkcs12(pfxBytes, pwd, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

}
catch (CryptographicException)
{
var pfxBytes = File.ReadAllBytes(pfxFile);
certificate = X509CertificateLoader.LoadPkcs12(pfxBytes, "", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

// success using blank pwd, continue with blank pwd
pwd = "";
}
#else
try
{
certificate = new X509Certificate2(pfxFile, pwd, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
}
Expand All @@ -384,6 +401,7 @@ public static async Task<X509Certificate2> StoreCertificate(
// success using blank pwd, continue with blank pwd
pwd = "";
}
#endif

if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Expand Down Expand Up @@ -790,7 +808,14 @@ private static string GetWindowsPrivateKeyLocation(string keyFileName)
}

public static X509Store GetMachineStore(string storeName = DEFAULT_STORE_NAME) => new X509Store(storeName, StoreLocation.LocalMachine);
public static X509Store GetUserStore(string storeName = DEFAULT_STORE_NAME) => new X509Store(storeName, StoreLocation.CurrentUser);
public static X509Store GetUserStore(string storeName = DEFAULT_STORE_NAME)
{
#if NET9_0_OR_GREATER
return new X509Store(storeName, StoreLocation.CurrentUser, OpenFlags.ReadWrite);
#else
return new X509Store(storeName, StoreLocation.CurrentUser);
#endif
}

public static bool IsCertificateInStore(X509Certificate2 cert, string storeName = DEFAULT_STORE_NAME)
{
Expand Down

0 comments on commit 6cfcb0a

Please sign in to comment.