【发布时间】:2023-03-29 08:40:02
【问题描述】:
首先,我知道有人提出了非常相似的问题,但是通读了解决方案并修改了我自己的工作流程并没有产生正确的结果。
我希望通过显示我正在使用的代码,有人可以指出我哪里出错了。我正在尝试将我的 Windows 10 机器上的私有密钥导入安装了 powershell 版本 2 的旧版 Windows 7。
我面临的错误是 $cert.hasprivatekey 返回 true 但 $cert.privatekey 总是返回 null。然而,这也发生在 Windows 10 机器上,所以生成密钥似乎是个问题,但我发现的每个指南都使用相同的语法!
这是创建密钥的代码:
$store = "cert:\CurrentUser\My"
$params = @{
CertStoreLocation = $store
Subject = "CN=Test1"
KeyLength = 2048
KeyAlgorithm = "RSA"
KeyUsage = "DataEncipherment"
Type = "DocumentEncryptionCert"
KeyExportPolicy = 'Exportable'
}
# generate new certificate and add it to certificate store
$cert = New-SelfSignedCertificate @params
Get-ChildItem -path $store
$pwd = ("P@ssword" | ConvertTo-SecureString -AsPlainText -Force)
$privateKey = "$home\Documents\Test1.pfx"
$publicKey = "$home\Documents\Test1.cer"
# Export private key as PFX certificate, to use those Keys on different machine/user
Export-PfxCertificate -FilePath $privateKey -Cert $cert -Password $pwd
# Export Public key, to share with other users
Export-Certificate -FilePath $publicKey -Cert $cert
我也试过了,没用:
$TestCertificate = New-SelfSignedCertificate -Subject 'TestCertificate' -KeyExportPolicy 'Exportable'
Export-PfxCertificate -Cert $TestCertificate -FilePath .\TestCertificate.pfx -Password (ConvertTo-SecureString 'TestPassword' -AsPlainText -Force)
然后我尝试使用以下方法在 Windows 7 上导入私有 pfx 证书:
$PfxFilePath = "C:\Users\user\Desktop\Test1.pfx"
$pwd = ("P@ssword" | ConvertTo-SecureString -AsPlainText -Force)
$Password = $pwd
$absolutePfxFilePath = Resolve-Path -Path $PfxFilePath
Write-Output "Importing store certificate '$absolutePfxFilePath'..."
Add-Type -AssemblyName System.Security
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$cert.Import($absolutePfxFilePath, $Password, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]"PersistKeySet")
$Store = New-Object System.Security.Cryptography.X509Certificates.X509Store(
[System.Security.Cryptography.X509Certificates.StoreName]::My,
[System.Security.Cryptography.X509Certificates.StoreLocation]::LocalMachine)
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::"ReadWrite")
$store.Add($cert)
$store.Close()
欢迎所有想法!
【问题讨论】:
标签: powershell x509certificate private-key