From d6adc535de61584d00eef61da2921826354569f4 Mon Sep 17 00:00:00 2001
From: embetten <53092095+embetten@users.noreply.github.com>
Date: Thu, 19 Sep 2024 14:26:39 -0700
Subject: [PATCH] Adding pem certificate support for dotnet 6 or higher (#518)
Adding support for .pem certificates to address [artifacts-keyring
issue](https://github.com/microsoft/artifacts-keyring/issues/60). Note
this is only targeting .net 6 or greater versions of the cred provider,
since the `CreateFromPemFile` is only available in .net 5 or greater.
Otherwise, we have to implement reading the pem ourselves.
Additional Considerations:
- Add certificate passwords for pfx files.
---
CredentialProvider.Microsoft/Resources.resx | 6 ++++++
.../Util/CertificateUtil.cs | 18 +++++++++++++++++-
2 files changed, 23 insertions(+), 1 deletion(-)
diff --git a/CredentialProvider.Microsoft/Resources.resx b/CredentialProvider.Microsoft/Resources.resx
index b71a2873..23b49dcf 100644
--- a/CredentialProvider.Microsoft/Resources.resx
+++ b/CredentialProvider.Microsoft/Resources.resx
@@ -506,6 +506,12 @@ Provide MSAL Cache Location
Using certificate: {0}.
+
+ Certificate file type not supported. Only .pfx and .pem certificates are accepted.
+
+
+ Certificate file type .pem are only supported on versions of the credential provider built on .Net 6 or greater.
+
Using Entra tenant: {0}.
diff --git a/CredentialProvider.Microsoft/Util/CertificateUtil.cs b/CredentialProvider.Microsoft/Util/CertificateUtil.cs
index 0c5745be..a0424531 100644
--- a/CredentialProvider.Microsoft/Util/CertificateUtil.cs
+++ b/CredentialProvider.Microsoft/Util/CertificateUtil.cs
@@ -1,4 +1,5 @@
using System;
+using System.IO;
using System.Security.Cryptography.X509Certificates;
using ILogger = NuGetCredentialProvider.Logging.ILogger;
@@ -54,7 +55,22 @@ public static X509Certificate2 GetCertificateByFilePath(ILogger logger, string f
try
{
- var certificate = new X509Certificate2(filePath);
+ var fileType = Path.GetExtension(filePath);
+ X509Certificate2 certificate;
+ switch (fileType)
+ {
+ case ".pfx":
+ certificate = new X509Certificate2(filePath);
+ break;
+ case ".pem":
+#if NET6_0_OR_GREATER
+ certificate= X509Certificate2.CreateFromPemFile(filePath);
+ break;
+#endif
+ throw new NotSupportedException(Resources.ClientCertificatePemFilesNotSupported);
+ default:
+ throw new NotSupportedException(Resources.ClientCertificateFileTypeNotSupported);
+ }
if (certificate == null)
{