[英]How do I get the public key from a PFX certificate using Powershell?
I am trying to extract the public key from a certificate using Powershell. 我试图使用Powershell从证书中提取公钥。 However, whenever I use the Powershell command
Get-PfxCertificate
it only outputs the Thumbprint of the certificate and not the public key. 但是,每当我使用Powershell命令
Get-PfxCertificate
,它只输出证书的指纹而不是公钥。 How can I get it to output the public key? 如何让它输出公钥?
To retrieve the public key from a PFX certificate using Powershell, use the following command: 要使用Powershell从PFX证书检索公钥,请使用以下命令:
(Get-PfxCertificate -FilePath mycert.pfx).GetPublicKey()
To convert the public key to a hex string without hyphens you can use this command: 要将公钥转换为不带连字符的十六进制字符串,可以使用以下命令:
[System.BitConverter]::ToString((Get-PfxCertificate -FilePath mycert.pfx).GetPublicKey()).Replace("-", "")
Be aware, that Get-PfxCertificate
temporarily stores your private key at %ProgramData%\\Microsoft\\Crypto\\RSA\\MachineKeys
, where everyone could read it. 请注意,
Get-PfxCertificate
将您的私钥临时存储在%ProgramData%\\Microsoft\\Crypto\\RSA\\MachineKeys
, 每个人都可以阅读它。
If that is not a desirable behavior, than you should probably use either import
method or constructor of the X509Certificate2
.NET object with EphemeralKeySet
as a key storage flag, which indicates that private key should be created in memory and not persisted on disk when importing a certificate, eg: 如果这不是一个理想的行为,那么你应该使用
X509Certificate2
.NET对象的import
方法或构造函数与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
flag supported by .NET Framework 4.7.2 , .NET Core 2.0 and above; EphemeralKeySet
标志; $X509KeyStorageFlag = 32
is just a shorthand for the $X509KeyStorageFlag = [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::EphemeralKeySet
$X509KeyStorageFlag = 32
只是$X509KeyStorageFlag = [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::EphemeralKeySet
的简写 X509KeyStorageFlags
enumerator spec https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.x509certificates.x509keystorageflags X509KeyStorageFlags
枚举器规范https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.x509certificates.x509keystorageflags
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.