4

I am trying to extract the public key from a certificate using Powershell. However, whenever I use the Powershell command Get-PfxCertificate it only outputs the Thumbprint of the certificate and not the public key. How can I get it to output the public key?

4

2 回答 2

11

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

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

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

[System.BitConverter]::ToString((Get-PfxCertificate -FilePath mycert.pfx).GetPublicKey()).Replace("-", "")
于 2016-06-30T23:18:36.113 回答
5

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

如果这不是一个可取的行为,那么您可能应该使用.NET 对象import的方法或构造函数作为密钥存储标志,这表明私钥应该在内存中创建,而不是在导入证书时保存在磁盘上,例如:X509Certificate2EphemeralKeySet

$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

进一步阅读

于 2019-02-09T17:33:38.663 回答