Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 290
user1335978 Avatar asked Jul 13 '17 19:07

user1335978


1 Answers

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)
like image 163
Eienkei Avatar answered Sep 20 '22 17:09

Eienkei