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

使用PowerShell在Windows生成PEM格式自签名证书时遇“Invalid provider type specified”错误求助

使用PowerShell在Windows生成PEM格式自签名证书时遇“Invalid provider type specified”错误求助

看起来你遇到的这个「Invalid provider type specified」错误,大概率是因为默认生成的自签名证书用了不兼容的加密服务提供程序(CSP),导致PSPKI模块的Convert-PfxToPem工具没法正确读取和转换私钥。我来帮你调整脚本解决这个问题:

问题根源

默认情况下,New-SelfSignedCertificate会使用Microsoft RSA SChannel Cryptographic Provider来生成证书,这个Provider的私钥在导出转换时容易出现兼容性问题,而且默认生成的证书私钥不可导出(虽然你用Export-PfxCertificate成功导出了PFX,但底层的CSP类型还是不兼容PSPKI的转换逻辑)。

修复方案

生成证书时,我们需要指定两个关键参数:

  • KeyExportPolicy = 'Exportable':明确允许私钥被导出
  • KeyProviderName = 'Microsoft Enhanced RSA and AES Cryptographic Provider':使用兼容性更好的加密服务提供程序

修正后的完整脚本

Import-Module PSPKI

Write-Host "Create Windows Certificate"

$paramsCreate = @{
    DnsName = 'localhost'
    CertStoreLocation = 'Cert:\LocalMachine\My'
    # 新增:允许私钥导出
    KeyExportPolicy = 'Exportable'
    # 新增:使用兼容的加密服务提供程序
    KeyProviderName = 'Microsoft Enhanced RSA and AES Cryptographic Provider'
}

$cert = New-SelfSignedCertificate @paramsCreate

Write-Host "Create Password"

$mypwd = ConvertTo-SecureString -String '1234' -Force -AsPlainText

Write-Host "Export Certificate as Pfx"

$paramsExport = @{
    Cert = $cert
    FilePath = 'C:\temp.pfx'
    Password = $mypwd
}

Export-PfxCertificate @paramsExport

Write-Host "Convert pfx to pem"

Convert-PfxToPem -InputFile 'C:\temp.pfx' -Password $mypwd -Outputfile 'C:\tmp.pem'

(Get-Content 'C:\tmp.pem' -Raw) -match "(?ms)(\s*((?<privatekey>-----BEGIN PRIVATE KEY-----.*?-----END PRIVATE KEY-----)|(?<certificate>-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----))\s*){2}"

$Matches["privatekey"] | Set-Content "C:\key.pem"
$Matches["certificate"] | Set-Content "C:\cert.pem"

额外说明

如果你的环境里安装了OpenSSL,也可以用它来替代PSPKI的转换步骤,命令更简洁:

# 导出私钥到key.pem
openssl pkcs12 -in C:\temp.pfx -nocerts -out C:\key.pem -passin pass:1234 -passout pass:1234
# 导出证书到cert.pem
openssl pkcs12 -in C:\temp.pfx -clcerts -nokeys -out C:\cert.pem -passin pass:1234

不过前提是你已经把OpenSSL添加到系统环境变量里了。

备注:内容来源于stack exchange,提问作者peni4142

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.20 08:50:30