如何使用Powershell从PFX证书获取公钥?

如何使用Powershell从PFX证书获取公钥?,powershell,certificate,public-key,pkcs12,Powershell,Certificate,Public Key,Pkcs12,我正在尝试使用Powershell从证书中提取公钥。但是,每当我使用Powershell命令时,它只输出证书的指纹,而不是公钥。如何使其输出公钥?要使用Powershell从PFX证书检索公钥,请使用以下命令: (Get-PfxCertificate -FilePath mycert.pfx).GetPublicKey() 要将公钥转换为不带连字符的十六进制字符串,可以使用以下命令: [System.BitConverter]::ToString((Get-PfxCertificate -Fi

我正在尝试使用Powershell从证书中提取公钥。但是,每当我使用Powershell命令时,它只输出证书的指纹,而不是公钥。如何使其输出公钥?

要使用Powershell从PFX证书检索公钥,请使用以下命令:

(Get-PfxCertificate -FilePath mycert.pfx).GetPublicKey()
要将公钥转换为不带连字符的十六进制字符串,可以使用以下命令:

[System.BitConverter]::ToString((Get-PfxCertificate -FilePath mycert.pfx).GetPublicKey()).Replace("-", "")

请注意,
Get-PfxCertificate
将您的私钥临时存储在
%ProgramData%\Microsoft\Crypto\RSA\MachineKeys
,每个人都可以在这里阅读

如果这不是一个理想的行为,那么您可能应该使用
import
方法或
X509Certificate2
.NET对象的构造函数,将
EphemeralKeySet
作为密钥存储标志,该标志指示在导入证书时应在内存中创建私钥,而不是在磁盘上持久化,例如:

$Cert=新对象-TypeName System.Security.Cryptography.X509Certificates.X509Certificate2
$FullPathToCert=解析路径-路径。\cert.pfx
$Password=读取主机“密码”-AsSecureString
$X509KeystrageFlag=32
$Cert.Import($FullPathToCert,$Password,$x509keystargeflag)
$Cert.GetPublicKey()
笔记
  • EphemeralKeySet
    标志受.NET Framework 4.7.2、.NET Core 2.0及以上版本支持
  • $x509keystargeflag=32
    只是
    $x509keystargeflag=[System.Security.Cryptography.X509Certificates.x509keystargeflags]的简写::EphemeralKeySet
进一步阅读
  • X509keystrageFlags
    枚举器规范
  • 在.NET中使用X.509证书的八个技巧: