Skip to content
Next Next commit
x509: add utils to find certs by thumbprint
  • Loading branch information
mjcheetham committed Aug 15, 2023
commit 667698614ff6fb854bccb37e0c7fc904bd439d28
23 changes: 23 additions & 0 deletions src/shared/Core/X509Utils.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System.Security.Cryptography.X509Certificates;

namespace GitCredentialManager;

public static class X509Utils
{
public static X509Certificate2 GetCertificateByThumbprint(string thumbprint)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here's a slight more battle tested way to load certs. I think this is fine for loading by thumbprint, but if loading by name you should exclude expired certs and load the most fresh.

https://github.com/AzureAD/microsoft-identity-web/blob/96323e40bc6e6610192461f7b1dfaf4c2605ff21/src/Microsoft.Identity.Web.Certificate/CertificateLoaderHelper.cs#L55

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a compelling argument for allowing people to specify something other than a thumbprint (like the cert name, or file path)? Are there common situations where the thumbprint would not be known?

I guess at certificate renewal a new thumbprint would be created, but the certificate would have the same name?

Right now we only have credential.azreposServicePrincipalCertificateThumbprint / GCM_AZREPOS_SP_CERT_THUMBPRINT to specify a thumbprint.

We could add other options like ..CertificatePath / .._CERT_PATH and ..CertificateName / .._CERT_NAME in the future (unless you think it's useful from the get go!) :)

{
foreach (var location in new[]{StoreLocation.CurrentUser, StoreLocation.LocalMachine})
{
using var store = new X509Store(StoreName.My, location);
store.Open(OpenFlags.ReadOnly);

X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);
if (certs.Count > 0)
{
return certs[0];
}
}

return null;
}
}