powershellx509certificatex509x509certificate2azure-keyvault

Powershell "X509Certificate2Collection" Exception calling "Import" with "3" argument(s): "Cannot find the requested object


I have the below piece of code to download cert from Azure Key Vault.

   $secretName = "TestCert"
    $kvSecret = Get-AzureKeyVaultSecret -VaultName $vaultName -Name $certificateName
    $kvSecretBytes = [System.Convert]::FromBase64String($kvSecret.SecretValueText)
    $certCollection = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection
    $certCollection.Import($kvSecretBytes,$null, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)

But While importing cert to the certCollection the import method is throwing below error.

Exception calling "Import" with "3" argument(s): "Cannot find the requested object.
"
At C:\Users\abc\Desktop\test2.ps1:8 char:1
+ $certCollection.Import($kvSecretBytes,$null,[System.Security.Cryptogr ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : CryptographicException     

Greatly appreciate help with this. Thanks


Solution

  • Change the code like this and you are good to go!

        $secretName = "TestCert"
        $kvSecret = Get-AzureKeyVaultSecret -VaultName $vaultName -Name $certificateName
        $kvSecretBytes = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($kvSecret.SecretValueText))
        $jsonCert = ConvertFrom-Json($kvSecretBytes)
        $certBytes = [System.Convert]::FromBase64String($jsonCert.data)
        $certCollection = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection
        $certCollection.Import($certBytes,$jsonCert.password,[System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)