从 pfx 文件或证书存储中提取私钥,无需在 Windows 上使用 OpenSSL

问题描述 投票:0回答:7

正如标题所示,我想在不使用 OpenSSL 或任何其他第三方工具的情况下导出我的私钥。如果我需要

.cer
文件或
.pfx
文件,我可以通过 MMC 或 PowerShell 轻松导出这些文件
pkiclient
,但我找不到获取私钥的方法。

https://learn.microsoft.com/en-us/powershell/module/pkiclient/export-certificate?view=win10-ps

使用像 https://www.sslshopper.com/ssl-converter.html 这样的在线工具是不行的。

PS版本:

PS C:\Users\oscar> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.17134.228
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.17134.228
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

我可以这样获取公钥:

(Get-PfxCertificate -FilePath C:\Users\oscar\Desktop\localhost.pfx).GetPublicKey()

并像这样导出整个证书:

(Get-PfxCertificate -FilePath C:\Users\oscar\Desktop\localhost.pfx).GetRawCertData()

结果来自

PS C:\Users\oscar> $mypwd = ConvertTo-SecureString -String "MyPassword" -Force -AsPlainText
PS C:\Users\oscar> $mypfx = Get-PfxData -FilePath C:\Users\oscar\Desktop\localhost.pfx -Password $mypwd
PS C:\Users\oscar> $mypfx

OtherCertificates EndEntityCertificates
----------------- ---------------------
{}                {[Subject]...


PS C:\Users\oscar> $mypfx.EndEntityCertificates

Thumbprint                                Subject
----------                                -------
8ED4971564E35099D6DB490C3756E2AD43AAAAAA  CN=localhost

测试了@Brad 的命令,但出现了以下错误。

私钥不可以纯文本形式导出

certutil -exportPFX -p "myPassword" -privatekey -user my <Certificate Serial Number> C:\localhost.pfx

与 MMC 证书中的证书导出向导类似,仅导出到包含密钥时可用的

.pfx

windows powershell certificate certificate-store
7个回答
16
投票

我遇到了同样的问题,并在 PS Gallery 的 PSPKI Powershell 模块 的帮助下解决了它。虽然我知道您正在寻找一种最好使用 Windows 中某些内置功能的解决方案,但从 PS Gallery 安装模块可能是可以接受的。至少我的情况是这样。

首先安装 PSPKI 模块(我假设 PSGallery 存储库已经设置好):

Install-Module -Name PSPKI

PSPKI 模块提供了一个 Cmdlet

Convert-PfxToPem
,它将 pfx 文件转换为 pem 文件,其中包含证书和私有密钥作为 base64 编码文本:

Convert-PfxToPem -InputFile C:\path\to\pfx\file.pfx -Outputfile C:\path\to\pem\file.pem

现在,我们需要做的就是使用一些正则表达式魔法来分割 pem 文件。例如,像这样:

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

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

5
投票

我发现Panos.G的答案很有希望,但没有让它发挥作用。所有描述的三种方法在我的证书对象上均不可用。经过更多挖掘,我想出了以下解决方案:

注意:如果您从证书存储中读取证书,它就可以工作。例如,如果您使用

.pfx
读取
Get-PfxCertificate
文件,则它不起作用。如果您只是将其作为文件,则可以将其安装在证书存储中,以便能够从那里读取它,如下所示。

# Read the certificate from the certificate store
# In this example, I use the certificate thumbprint to identify the certificate.
$cert = Get-ChildItem Cert:\ -Recurse | ? {$_.Thumbprint -eq '<THUMBPRINT_OF_CERTIFICATE>'}

# Read the private key into an RSA CNG object:
$RSACng = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($cert)

# Get the bytes of the private key
$KeyBytes = $RSACng.Key.Export([System.Security.Cryptography.CngKeyBlobFormat]::Pkcs8PrivateBlob)

# Encode the bytes (Base64)
$KeyBase64 = [System.Convert]::ToBase64String($KeyBytes, [System.Base64FormattingOptions]::InsertLineBreaks)

# Put it all together
$KeyPem = @"
-----BEGIN PRIVATE KEY-----
$KeyBase64
-----END PRIVATE KEY-----
"@

文档:


3
投票

基于 stackprotector 的 现有答案我想添加一个在直接从 .pfx 文件读取时起作用的片段。

从文件读取时,必须使用 .net core 中允许指定 X509StorageFlag Exportable 的方法,而不是使用 PowerShells Get-PfxCertificate

# Password is a plain string, not a securestring
$cert=New-Object System.Security.Cryptography.X509Certificates.X509Certificate2( 
      $filename, 
      $password, 
      [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)

# now continue as with the other solutions
# Read the private key into an RSA CNG object:
$RSACng = [Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($cert)

# Get the bytes of the private key
$KeyBytes = $RSACng.Key.Export([Security.Cryptography.CngKeyBlobFormat]::Pkcs8PrivateBlob)

# Encode the bytes (Base64)
$KeyBase64 = [Convert]::ToBase64String($KeyBytes, [Base64FormattingOptions]::InsertLineBreaks)

# Put it all together
$KeyPem = @"
-----BEGIN PRIVATE KEY-----
$KeyBase64
-----END PRIVATE KEY-----
"@

1
投票

基于 PowerShellGuy 提到的内容。

这对你有用吗?

# first get your cert, either via pure .NET, or through the PSDrive (Cert:\)

# this is just an example

# get cert from PSDrive
$cert = Get-ChildItem Cert:\LocalMachine\My | where Subject -eq 'CN=MySubject'

# get cert from .NET
$My     = [System.Security.Cryptography.X509Certificates.StoreName]::My
$Store  = [System.Security.Cryptography.X509Certificates.X509Store]::new($My,'localmachine')
$Store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::MaxAllowed)

$cert   = $Store.Certificates | where Subject -eq 'CN=MySubject'

# get private key
# PKCS8, way #1
$BytesPkcs8 = $cert.PrivateKey.ExportPkcs8PrivateKey()
[System.Convert]::ToBase64String($BytesPkcs8)

# PKCS8, way #2
$Pkcs = [System.Security.Cryptography.CngKeyBlobFormat]::Pkcs8PrivateBlob
$BytesPkcs8 = $cert.PrivateKey.Key.Export($Pkcs)
[System.Convert]::ToBase64String($BytesPkcs8)

# RSA
$BytesRsa = $cert.PrivateKey.ExportRSAPrivateKey()
[System.Convert]::ToBase64String($BytesRsa)

那么 Base64 字符串就是您要找的吗?


0
投票

嗯。您是否尝试过打开证书存储并以这种方式获取私钥?很确定这仅适用于 RSA/DSA 证书。

$store = New-Object System.Security.Cryptography.X509Certificates.X509Store([System.Security.Cryptography.X509Certificates.StoreName]::My,"localmachine")
$store.Open("MaxAllowed")
$cert = $store.Certificates | ?{$_.subject -match "^CN=asdasd"}
$cert.PrivateKey.ToXmlString($false)
$store.Close()


0
投票

使用脚本识别要导出的证书,由指纹识别第一行用于查找指纹,这是您需要编辑的唯一行,将 yourthumbprintID 替换为证书指纹

获取子项证书:\LocalMachine\My
$cert = get-item "cert:\localmachine\my\YourcertshumbprintID"

Base64 的公钥

$CertBase64 = [System.Convert]::ToBase64String($cert.RawData, [System.Base64FormattingOptions]::InsertLineBreaks)

Base64 的私钥

$RSACng = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($cert) $KeyBytes = $RSACng.Key.Export([System.Security.Cryptography.CngKeyBlobFormat]::Pkcs8PrivateBlob) $KeyBase64 = [System.Convert]::ToBase64String($KeyBytes, [System.Base64FormattingOptions]::InsertLineBreaks)

把它们放在一起

$Pem = @" -----开始私钥----- $KeyBase64 -----结束私钥----- -----开始证书----- $CertBase64 -----证书结束----- “@

输出到文件

$Pem |输出文件-FilePath cert.pem -编码 Ascii


-1
投票

如果我理解正确的话 certutil 应该为你做。

certutil -exportPFX -p "ThePasswordToKeyonPFXFile" my [serialNumberOfCert] [fileNameOfPFx]

© www.soinside.com 2019 - 2024. All rights reserved.