使用私钥 Export-Clixml 从对象导出证书

Export certificate from object with private key Export-Clixml

我正在尝试将一些对象存储为 PowerShell 中的 Clixml。

我可以成功存储我的数组和证书,但是私钥没有导出。

示例:

PS > $cert.HasPrivateKey
true

PS > $outObject = $array
PS > $outObject += $cert
PS > $outObject | Export-Clixml -Path .\file.xml

PS > $inObject = Import-Clixml -Path .\file.xml
PS > $newcert = $inObject | Where-Object { $_.GetType().Name -like "*X509Certificate2" }

PS > $newcert.HasPrivateKey
false

我注意到有一个方法 $cert.PrivateKey:

ExportParameters     Method     System.Security.Cryptography.RSAParameters ExportParameters(bool includePrivateParameters)

此脚本在 Windows 中并未具体 运行 并且证书未安装在 CABI 存储中,仅从 Get-PfxCertificate.

导入的变量

长话短说,我正在构建一个连接到 API 并带有客户端身份验证的模块。我正在尝试从 Clixml 文件中提取客户端身份验证。

私钥不是 X509Certificate2 对象的一部分,因此它不会与 public 证书一起导出。私钥链接到 public 证书。

为了导出带有私钥的证书,您必须先序列化证书和私钥对象,然后再将其传递给 Export-CliXml

使用X509Certificate2.Export(X509Content​Type, Secure​String) 方法将带有关联私钥的证书导出到 PFX(PKCS#12 容器)。私钥 material 受密码保护。

调用 Import-CliXml cmdlet 后,使用 X509Certificate2.Import(Byte[], Secure​String, X509Key​Storage​Flags) 方法导入证书和关联的私钥。

这是您唯一的选择。另外,请注意,此方法仅在私钥可导出时才有效。如果私钥不可导出,Export 方法将失败。

通过将证书对象转换为 PFX 格式(按照 Crypt32 的建议)并将我的对象保存在哈希中 table 我能够使用私钥成功导出和导入数组和证书。

PS > $cert.HasPrivateKey                                                             
true

PS > $pfx = $cert.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pfx,'Pa$$w0rd')
PS > $outObject = @{
>> myArray = $array
>> myCert = $pfx 
>> }

PS > Export-Clixml -InputObject $outObject -Path .\file.xml


PS > $inObject = Import-Clixml -Path .\file.xml   
PS > $newCert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::New($inObject.myCert,'Pa$$w0rd')
PS > $newCert.HasPrivateKey
true