如何通过PowerShell或.NET命令获取Windows证书存储中证书的Description属性?
如何通过PowerShell或.NET命令获取Windows证书存储中证书的Description属性?
嗨,兄弟,我完全懂你的烦恼——默认用Get-ChildItem拉取证书后,Select *确实看不到这个Description属性,它要么藏在证书扩展的友好名称里,要么是存储层面的元数据,默认没暴露出来。分两种情况给你解决办法:
情况1:你要的是Details标签里「Enhanced Key Usage」对应的描述文本
其实你已经拿到这个数据了!你输出里的EnhancedKeyUsageList就是它,只是默认显示的是带OID的组合字符串,单独提取友好名称就行:
$certs = Get-ChildItem Cert:\LocalMachine\My\ # 提取目标证书的Enhanced Key Usage描述 $certs[2].EnhancedKeyUsageList | Select-Object FriendlyName, Oid
运行后会得到这样的输出:
FriendlyName Oid ----------- --- Authentication du serveur 1.3.6.1.5.5.7.3.1
这里的FriendlyName就是你在Details标签里看到的Description内容。
情况2:你要的是证书存储中手动添加的自定义Description注释(存储元数据)
这个是存在证书存储里的附加信息,不是证书本身的内容,得调用系统底层API来读取。我给你写了个PowerShell的小脚本,直接用就行:
# 先导入自定义的证书工具类 Add-Type @" using System; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; public class CertUtils { [DllImport("crypt32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern bool CertGetCertificateContextProperty( IntPtr pCertContext, uint dwPropId, IntPtr pvData, ref uint pcbData); private const uint CERT_DESCRIPTION_PROP_ID = 0x00000001; public static string GetCertificateDescription(X509Certificate2 cert) { uint dataSize = 0; // 先获取缓冲区大小 CertGetCertificateContextProperty(cert.Handle, CERT_DESCRIPTION_PROP_ID, IntPtr.Zero, ref dataSize); if (dataSize == 0) return null; IntPtr buffer = Marshal.AllocHGlobal((int)dataSize); try { if (CertGetCertificateContextProperty(cert.Handle, CERT_DESCRIPTION_PROP_ID, buffer, ref dataSize)) { return Marshal.PtrToStringAuto(buffer); } return null; } finally { Marshal.FreeHGlobal(buffer); } } } "@ # 调用工具类获取Description $certs = Get-ChildItem Cert:\LocalMachine\My\ $targetCert = $certs[2] $description = [CertUtils]::GetCertificateDescription($targetCert) # 输出结果 if ($description) { Write-Host "证书的自定义Description:$description" } else { Write-Host "该证书没有设置自定义Description" }
要是用.NET代码(比如C#)的话,逻辑和上面的PowerShell导入的类完全一样,直接把CertUtils类的代码抄过去调用就行。
备注:内容来源于stack exchange,提问作者Théo Fleury
相关产品推荐
相关产品推荐

