Skip to content

Commit 8b6d426

Browse files
Load macOS Key Vault certs as Exportable only so private key survives export (#5259)
On macOS, loading the Key Vault PKCS#12 with PersistKeySet imports the private key into the login Keychain, which cannot export the private key back out. That produced public-only PFX exports (~half the expected size) with no private key, breaking both the file-backed cert store and the base64 certs written to stdout. Select storage flags by OS: use Exportable only on macOS (no PersistKeySet) so the key stays in memory and can be exported to the file-backed store; keep Exportable | PersistKeySet on Windows/Linux. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 7c16da2 commit 8b6d426

1 file changed

Lines changed: 11 additions & 2 deletions

File tree

src/tools/CertHelper/KeyVaultCert.cs

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
using System.IO;
99
using System.Linq;
1010
using System.Runtime.CompilerServices;
11+
using System.Runtime.InteropServices;
1112
using System.Security.Cryptography.X509Certificates;
1213
using System.Text;
1314
using System.Threading.Tasks;
@@ -149,10 +150,18 @@ private async Task<X509Certificate2> FindCertificateInKeyVaultAsync(string certN
149150
throw new Exception("Certificate secret not found in Key Vault");
150151
}
151152
var certBytes = Convert.FromBase64String(secret.Value.Value);
153+
154+
// On macOS, PersistKeySet imports the private key into the login Keychain, which then cannot
155+
// export the private key back out (the same limitation the file-backed store works around).
156+
// That produces public-only PFX exports (roughly half the expected size). Load the key as
157+
// Exportable only so it stays in memory and can be exported to the file-backed store.
158+
var storageFlags = RuntimeInformation.IsOSPlatform(OSPlatform.OSX)
159+
? X509KeyStorageFlags.Exportable
160+
: X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet;
152161
#if NET9_0_OR_GREATER
153-
var cert = X509CertificateLoader.LoadPkcs12(certBytes, "", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
162+
var cert = X509CertificateLoader.LoadPkcs12(certBytes, "", storageFlags);
154163
#else
155-
var cert = new X509Certificate2(certBytes, "", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
164+
var cert = new X509Certificate2(certBytes, "", storageFlags);
156165
#endif
157166
return cert;
158167
}

0 commit comments

Comments
 (0)