You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PowerShell从证书存储中读取证书的KeySpec值

PowerShell获取证书存储中证书KeySpec值的实现方法

核心对应关系

传统CSP存储的RSA证书的KeySpec属性,对应.NET类型System.Security.Cryptography.RSACryptoServiceProvider下CspKeyContainerInfo.KeyNumber枚举,值对应规则:

  • 1 = AT_KEYEXCHANGE
  • 2 = AT_SIGNATURE

单证书查询示例

首先获取目标证书,以下示例按证书指纹从本地计算机个人存储读取证书,需替换为实际的证书指纹:

# 获取目标证书
$cert = Get-Item "Cert:\LocalMachine\My\替换为你的证书指纹"

提取并判断KeySpec:

if ($cert.PrivateKey -is [System.Security.Cryptography.RSACryptoServiceProvider]) {
    $keySpec = $cert.PrivateKey.CspKeyContainerInfo.KeyNumber.value__
    if ($keySpec -eq 1) {
        Write-Host "证书KeySpec已设置为AT_KEYEXCHANGE"
    } else {
        Write-Host "证书KeySpec为AT_SIGNATURE,值为:$keySpec"
    }
} elseif ($cert.PrivateKey -is [System.Security.Cryptography.RSACng]) {
    Write-Host "该证书使用CNG密钥存储,无传统KeySpec属性"
} else {
    Write-Host "未识别的私钥存储类型"
}

批量查询示例

遍历本地计算机个人存储下所有证书的KeySpec:

Get-ChildItem "Cert:\LocalMachine\My" -Recurse | ForEach-Object {
    $keySpec = $null
    $isAtKeyExchange = $false
    if ($_.PrivateKey -is [System.Security.Cryptography.RSACryptoServiceProvider]) {
        $keySpec = $_.PrivateKey.CspKeyContainerInfo.KeyNumber.value__
        $isAtKeyExchange = $keySpec -eq 1
    }
    [PSCustomObject]@{
        证书主题 = $_.Subject
        证书指纹 = $_.Thumbprint
        有效期至 = $_.NotAfter
        KeySpec值 = $keySpec
        是否为AT_KEYEXCHANGE = $isAtKeyExchange
    }
} | Format-Table -AutoSize

注意事项

  • 访问本地计算机证书存储需要以管理员身份运行PowerShell,否则可能无法读取私钥信息
  • 该方法直接调用.NET原生接口,不依赖certutil工具的输出格式,兼容所有Windows 7及以上系统的PowerShell 3.0+环境
  • 仅使用传统CSP存储的RSA证书存在KeySpec属性,使用新一代CNG密钥存储的证书无该属性

内容的提问来源于stack exchange,提问作者Robert

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 16:39:01