如何使用 Powershell 从 PFX 证书中获取 public 密钥?

How do I get the public key from a PFX certificate using Powershell?

我正在尝试使用 Powershell 从证书中提取 public 密钥。但是,每当我使用 Powershell 命令 Get-PfxCertificate 时,它只输出证书的指纹而不是 public 密钥。我怎样才能让它输出 public 键?

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

(Get-PfxCertificate -FilePath mycert.pfx).GetPublicKey()

要将 public 密钥转换为不带连字符的十六进制字符串,您可以使用此命令:

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

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

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

$Cert = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2
$FullPathToCert = Resolve-Path -Path .\cert.pfx
$Password = Read-Host 'Password' -AsSecureString
$X509KeyStorageFlag = 32
$Cert.Import($FullPathToCert, $Password, $X509KeyStorageFlag)
$Cert.GetPublicKey()

备注

  • EphemeralKeySet 标志受 .NET Framework 4.7.2.NET Core 2.0 及更高版本支持;
  • $X509KeyStorageFlag = 32 只是 $X509KeyStorageFlag = [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::EphemeralKeySet
  • 的 shorthand

进一步阅读