10

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

user1335978
  • 193
  • 4
  • 13

1 Answers1

6

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)
Eienkei
  • 84
  • 2
  • Yes just got this from one of my colleagues. and thank you so much for sharing this piece of code here. and yes its working. – user1335978 Jul 20 '17 at 00:12
  • @Eienkei, I am getting this error: "Import" with "3" argument(s): "The parameter is incorrect.". Kindly look if you can help. Thanks – Deepak Tatyaji Ahire Apr 29 '19 at 11:35
  • @DeepakTatyajiAhire did you manage to solve this? i have encountered the same problem. The parameter is incorrect. – Orenger Apr 22 '20 at 11:09
  • This only fixes cannot find requested object. if you have another issue related its probably because you use Get-AzureKeyVaultCertificate instead of a secret – Orenger Apr 22 '20 at 11:38
  • This is also useful https://thomasrayner.ca/how-to-retrieve-a-certificate-from-azure-key-vault-via-powershell/ #justsaying – Kyle Apr 30 '21 at 14:19