首页 > 解决方案 > 使用 PowerShell 从证书中检索 KeySpec 值

问题描述

我正在尝试验证机器商店中的证书已KeySpec设置为AT_KEYEXCHANGE. Usingcertutil.exe确实提供了此信息,但需要进行字符串解析。我宁愿避免字符串解析,以避免对certutil.exe我不知道的输出假设在不同版本的 Windows 中总是正确的。

我查看了 和 的属性和System.Security.Cryptography.X509Certificates.X509Certificate2方法System.Security.Cryptography.X509Certificates.RSACertificateExtensions

如何从证书存储中的证书中检索 KeySpec?

标签: powershellcertificate

解决方案


在此处此处的帮助下,我能够找到 KeySpec 。CspKeyContainerInfo 类包含一个名为 KeyNumber 的属性,这就是 certutil 所指的 KeySpec。

我找到了两种方法。一种仅适用于 PowerShell 5,另一种适用于 PowerShell 5 和 7。

仅限 PowerShell 5

$Cert = (Get-ChildItem -Path Cert:\LocalMachine\My)[1]
$Cert.PrivateKey.CspKeyContainerInfo.KeyNumber

PowerShell 5 和 7

$Cert = (Get-ChildItem -Path Cert:\LocalMachine\My)[1]
$PrivateKey = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($Cert)
$CngProvider = [System.Security.Cryptography.CngProvider]::new($PrivateKey.Key.Provider)
$CngKey = [System.Security.Cryptography.CngKey]::Open($PrivateKey.Key.KeyName,  $CngProvider, [System.Security.Cryptography.CngKeyOpenOptions]::MachineKey)
$CspParameters = [System.Security.Cryptography.CspParameters]::New(1, $CngKey.Provider, $CngKey.KeyName)
$CspParameters.Flags = [System.Security.Cryptography.CspProviderFlags]::UseMachineKeyStore
$CspKeyContainerInfo = [System.Security.Cryptography.CspKeyContainerInfo]::New($CspParameters)
$CspKeyContainerInfo.KeyNumber

推荐阅读