ps/Modules/Alkami.Ops.Certificates/Cmdlets/GetCertNameByThumbprint.cs
2023-05-30 22:51:22 -07:00

51 lines
1.7 KiB
C#

using Alkami.Ops.Common.Cryptography;
using System;
using System.Management.Automation;
using System.Security.Cryptography.X509Certificates;
namespace Alkami.Ops.Certificates.cmdlets
{
/// <summary>
/// Gets the SimpleName for a given Thumbprint
/// </summary>
[Cmdlet("Get", "CertNameByThumbprint")]
[OutputType(typeof(string))]
public class GetCertNameByThumbprint : Cmdlet
{
[Parameter(Position = 0, Mandatory = true)]
public string thumbprint;
[Parameter(Position = 1, Mandatory = true)]
[ValidateSet("all", "my", "CertificateAuthority", "root", "trustedpeople")]
public string certStore;
protected override void ProcessRecord()
{
GetName(this.thumbprint, this.certStore);
}
public void GetName(string thumbprint, string certStore = "all")
{
var storesToSearch = new string[4];
if (certStore == "all")
{
storesToSearch = new string[] { "my", "CertificateAuthority", "root", "trustedpeople" };
}
else
{
storesToSearch = new string[] { certStore };
}
foreach (var storeString in storesToSearch)
{
StoreName.TryParse(storeString, true, out StoreName storeName);
X509Certificate2 certificate = CertificateHelper.FindCertificateByThumbprint(thumbprint, storeName, StoreLocation.LocalMachine, "localhost");
if (certificate != null)
{
WriteObject($"Found {certificate.GetNameInfo(X509NameType.SimpleName, false)} in {storeString}");
}
}
}
}
}