Search code examples
powershellssl-certificatepfx

New-SelfSignedCertificate does not generate an exportable key


I am trying to generate an exportable key with the New-SelfSignedCertificate cmdlet and I can't.

Here is my code:

$certFilePath = "C:\certs"
$certStoreLocation = "Cert:\LocalMachine\My"
$pwd = "p@ssw0rd"

$cert = New-SelfSignedCertificate `
    -KeyFriendlyName "Development Cert" `
    -KeyDescription "Development Cert" `
    -KeyAlgorithm "RSA" `
    -DnsName @("*.dev.local", "localhost") `
    -NotBefore (Get-Date).AddYears(-1) `
    -NotAfter (Get-Date).AddYears(50) `
    -KeyUsage CertSign, CRLSign, DataEncipherment, DigitalSignature, NonRepudiation `
    -KeyUsageProperty All `
    -KeyLength 2048 `
    -KeyLocation $certFilePath `
    -CertStoreLocation $certStoreLocation `
    -KeyExportPolicy Exportable `
    -KeyProtection None `
    -Type Custom

$certThumb = $cert.Thumbprint
$certPath = "$certStoreLocation\$certThumb"
$cert | Export-PfxCertificate -FilePath "$certFilePath\$certThumb.pfx" -Password (ConvertTo-SecureString -String $pwd -AsPlainText -Force)
Export-PfxCertificate : Cannot export non-exportable private key.
At line:24 char:9
+ $cert | Export-PfxCertificate -FilePath "$certFilePath\$certThumb.pfx ...
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Export-PfxCertificate], Win32Exception
    + FullyQualifiedErrorId : System.ComponentModel.Win32Exception,Microsoft.CertificateServices.Commands.ExportPfxCertificate

Note that I specifically tell it to generate an exportable key, and it doesn't.

Any ideas?


Solution

  • Removing the part that says:

    -KeyLocation $certFilePath `
    

    ...solves the issue.