I downloaded a PFX file from Azure Key Vault using the CLI:
az keyvault secret download -f jul15.pfx -n dlis-api-call-xxxx --vault-name dlisIpsTrial --subscription XXXXXXX
I'm trying to use the certificate in this code:
var handler = new WebRequestHandler();
var certificate = new X509Certificate2("jul15.pfx");
handler.ClientCertificates.Add(certificate);
handler.SslProtocols = SslProtocols.Tls12;
But I get an error in the new X509Certificate2("jul15.pfx"); line: System.Security.Cryptography.CryptographicException: Cannot find the requested object.
Here is the full trace:
System.Security.Cryptography.CryptographicException: Cannot find the requested object.
at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
at System.Security.Cryptography.X509Certificates.X509Utils._QueryCertFileType(String fileName)
at System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromFile(String fileName, Object password, X509KeyStorageFlags keyStorageFlags)
at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(String fileName)
at MultiMedia.Dlis.QueryDlisTool.Program.MakeRequest(Options options, String address, Byte[] imageBytes, NormalizedRectangle_1 crop, HashSet`1 requestedOutputs) in E:\DlisIps\src\MultiMedia.Dlis.QueryDlisTool\Program.cs:line 210
at MultiMedia.Dlis.QueryDlisTool.Program.Run(Options options, Byte[] imageBlob, NormalizedRectangle_1 crop, Dictionary`2 outputFeatures) in E:\DlisIps\src\MultiMedia.Dlis.QueryDlisTool\Program.cs:line 120
Any idea on how to resolve this error? Should I download a .cert file and associate it with key to make it a .pfx file? Should I download a .pem instead and try to make it a .pfx file?
Also, when I try to install my jul15.pfx I get this error:
Key vault certificates can be downloaded as secret. The certificate is base64 encoded. According to the documentation, you can specify the --encoding parameter. This should work for you:
az keyvault secret download `
--file jul15.pfx `
--encoding base64 `
--name dlis-api-call-xxxx `
--vault-name dlisIpsTrial `
--subscription XXXXXXX
Related
How to backup and restore the Azure Key vault that includes keys, secrets & cert along with RBAC?
One way is you can use Powershell or CLI to achieve this. after you have done an az login.
keys
Export-AzKeyVaultKey and Import-AzKeyVaultKey commands in Azure PowerShell or the az keyvault key export and az keyvault key import commands in Azure CLI to export and import keys and secrets.
Certs
Export-AzKeyVaultCertificate and Import-AzKeyVaultCertificate commands in Azure PowerShell or the az keyvault certificate export and az keyvault certificate import commands in Azure CLI.
RBAC policies
Get-AzKeyVaultAccessPolicy and Set-AzKeyVaultAccessPolicy commands in Azure PowerShell or the az keyvault show and az keyvault set-policy
CLI example of how to export the keys, certs and RBAC policies to a local file
# Authenticate to Azure
az login
# Export keys, secrets, and certificates from the key vault
keyVaultName="<key-vault-name>"
exportFolderPath="<export-folder-path>"
az keyvault key export --name "<key-name>" --vault-name $keyVaultName --file "$exportFolderPath/key.json"
az keyvault secret export --name "<secret-name>" --vault-name $keyVaultName --file "$exportFolderPath/secret.json"
az keyvault certificate export --name "<certificate-name>" --vault-name $keyVaultName --file "$exportFolderPath/certificate.json"
# Export RBAC policies from the key vault
keyVault=$(az keyvault show --name $keyVaultName)
accessPolicies=$keyVault.properties.accessPolicies
echo $accessPolicies > "$exportFolderPath/access-policies.json"
If you wanted to restore those from the local file to another key vault this will the CLI way to do it
az keyvault key import --name "<key-name>" --vault-name $keyVaultName --file "$exportFolderPath/key.json"
az keyvault secret import --name "<secret-name>" --vault-name $keyVaultName --file "$exportFolderPath/secret.json"
az keyvault certificate import --name "<certificate-name>" --vault-name $keyVaultName --file "$exportFolderPath/certificate.json"
accessPolicies=$(cat "$exportFolderPath/access-policies.json")
az keyvault set-policy --name $keyVaultName --access-policies $accessPolicies
To Back up and restore an entire keyvault
Backup-AzKeyVault -VaultName <vault_name> -FilePath <file_path>
Restore-AzKeyVault -VaultName <vault_name> -FilePath <file_path>
https://learn.microsoft.com/en-us/powershell/module/az.keyvault/backup-azkeyvault?view=azps-9.2.0
AS Ricky Gummadi said One way is you can use PowerShell or CLI to achieve this.
The other method to Backup and Restore keys, secrets, certificates is through Azure portal is as follows
To backup and restore the Azure Key vault follow the Reference Document.
Keys Backup in Key Vault:
In key vault select created keys and click on Download Backup
Secrets Backup in Key Vault:
Select created Secret then click on Download Backup
Certificates Backup in Key Vault:
Restore:
Select your key vault.
Go to the type of object (secret, key, or certificate) you want to restore.
Select Restore Backup.
Go to the location where you stored the encrypted blob.
Select OK.
Reference link
I want to update the key vault secret values by getting the function app default key and service bus connection string using PowerShell/CLI script.
So, can anyone please help me out on this issue.
Based on the above requirement, We have written the below PowerShell script to pull the function app key value (default & MasterKey), function app application setting (Azure webjob storage) value.
Using those key values the script will create a secrets in the respective key vault.
Here is the PowerShell Script:
$accountInfo = az account show
$accountInfoObject = $accountInfo | ConvertFrom-Json
$subscriptionId = $accountInfoObject.id
$resourceGroup = <ResourceGroupName>
$functionName = <functionName>
$vaultname=<vaultName>
$functionkeylist = az rest --method post --uri "https://management.azure.com/subscriptions/$subscriptionId/resourceGroups/$resourceGroup/providers/Microsoft.Web/sites/$functionName/host/default/listKeys?api-version=2018-11-01"
$keylistobject = $functionkeylist | ConvertFrom-Json
##To pull the functionapp specific setting
$appsetting=az functionapp config appsettings list --name $functionName --resource-group $resourceGroup --query "[?name=='AzureWebJobsStorage'].{Value:value}" -o tsv ##pulling specific functionappsetting
##This block will create the secrets for specific app setting & functionapp key
az keyvault secret set --name $functionName'defaultkey' --vault-name $vaultname --value $keylistobject.functionKeys.default
az keyvault secret set --name $functionName'masterkey' --vault-name $vaultname --value $keylistobject.masterKey
az keyvault secret set --name $functionName'webappstorage' --vault-name $vaultname --value $appsetting
Note:
In the above PowerShell we have pulled existing app setting AzureWebJobStorage created a secret in the keyvault. would suggest you change the $appsettings block with the respective functionapp appsetting to create a secret in keyvault.
Here is the sample output for reference:
Updated Answer:
Add the below code to above PowerShell script which will pull the service bus connection string app setting of functionapp & will store connection string value as secret in key vault.
$servucebusappsetting=az functionapp config appsettings list --name $functionName --resource-group $resourceGroup --query "[?name=='azfapsb_RootManageSharedAccessKey_SERVICEBUS'].{Value:value}" -o tsv ##app setting of service connection string will be in the format (<servicebusName>_RootManageSharedAccessKey_SERVICEBUS)
az keyvault secret set --name $functionName'ServiceBusConnectionString' --vault-name $vaultname --value $servucebusappsetting
I am creating azure function connecting to to execute PnP commands. I have created certificate as mentioned in the docs. I am always getting Cannot find certificate with this thumbprint in the certificate store.Exception :Type
Why this error is happening? Any settings need to be modified?
Regarding the issue, please refer to the following steps
Create the self signed certificate
New-PnPAzureCertificate -OutPfx pnp.pfx -OutCert pnp.cer
Create Azure AD application
Configure permissions
Office 365 SharePoint Online (Application Permission)
Sites.FullControl.All
TermStore.ReadWrite.All
User.ReadWriteAll
Upload your client certificate(cer file) to the AD application
Create Function
Upload your pfx file to Azure function
az webapp config ssl upload --certificate-file "e:\cert\pnp.pfx" --name "<function app name>" --resource-group "" --certificate-password "" --query thumbprint --output tsv
Configure Function to allow the function to read the certificate
az functionapp config appsettings set --name <app-name> --resource-group <resource-group-name> --settings WEBSITE_LOAD_CERTIFICATES=<comma-separated-certificate-thumbprints>
8 function code
Connect-PnPOnline -Tenant <>.onmicrosoft.com -ClientId <the appid of the ad application> -Thumbprint <comma-separated-certificate-thumbprints> -Url https://<>.sharepoint.com
I'm trying to import a .pfx certificate to an Azure keyvault but am having some issues.
Import-AzKeyVaultCertificate -VaultName "SecHash03" -Name "CodeSigning" -FilePath "\path\to\my\cert.pfx"
Results in:
Import-AzKeyVaultCertificate : Key not valid for use in specified state.
At line:1 char:1
+ Import-AzKeyVaultCertificate -VaultName SecHash03 -Name " ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Import-AzKeyVaultCertificate], CryptographicException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.KeyVault.ImportAzureKeyVaultCertificate
I'm requesting this cert from an Enterprise CA using certreq from a machine in the same domain as the CA. There is no password required to import the cert. Plan was to then upload that cert to the aforementioned Azure keyvault.
I tried using the Azure portal to import this cert and that works fine; import and usage both works well. So this is not an issue with Roles as suggested in another similar Stackoverflow answer (Importing certificate to Azure Key Vault: Key not valid for use in specified state).
Please advice!
As far as I know, when you import a pre-existing .pfx file cert to Azure key vault, you need to provide a password which is used for protecting the cert as you need to export the cert within the Private Key and include all certificates in the certificate path if possible. For example,
# Export the cert to a PFX with password
$password = ConvertTo-SecureString "Password!" -AsPlainText -Force
Export-PfxCertificate -Cert "cert:\CurrentUser\My\$($cert.Thumbprint)" -FilePath C:\temp\cert2.pfx -Password $password
# Upload to Key Vault
Import-AzureKeyVaultCertificate -VaultName noel-temp -Name cert2 -FilePath C:\temp\cert2.pfx -Password $password
Alternatively,
If you use a supported CA, you can even configure Key Vault to enroll
for certificates on your behalf. No leaking of keys! For simplicity,
the policy in these examples will be set to generate self-signed certs
from Key Vault.
# Have Key Vault create the certificate with a simple policy
$policy = New-AzureKeyVaultCertificatePolicy -SubjectName "CN=mycluster.southcentralus.cloudapp.azure.com" -IssuerName Self -ValidityInMonths 12
Add-AzureKeyVaultCertificate -VaultName noel-temp -Name cert1 -CertificatePolicy $policy
# Download the secret (private key information) associated with the cert
$secret = Get-AzureKeyVaultSecret -VaultName noel-temp -Name cert1
$secretBytes = [System.Convert]::FromBase64String($secret.SecretValueText)
[System.IO.File]::WriteAllBytes("C:\temp\cert1.pfx", $secretBytes)
# Import the certificate to CurrentUser\My
Import-PfxCertificate -FilePath C:\temp\cert1.pfx -CertStoreLocation cert:\CurrentUser\My -Exportable
You could get more details from these two links:
Importing Certificates to Key Vault
Manage certificates via Azure Key Vault
I am on Ubuntu 18.04, trying to use Azure CLI (2.0.56) to download Secret from Azure KeyVault. The download of the Secret works fine in Powershell on Windows but on Linux it fails with the following error:
'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)
The command itself:
az keyvault secret download -n secret-file --vault-name testkeyvault -f /usr/src/secret-file.json
I have tried to save the file with UNIX Line Endings, the encoding is UTF-8, I can open the file with cat in Linux, I can even set secret using the same file and az keyvault secret set in Linux but can't download it straight after.
Maybe this can help someone searching a similar issue. I believe the issue is with the implementation in Azure CLI. As a workaround I have used jq to parse the content of secret myself after using the show instead of download operation.
Here is the command to do that:
az keyvault secret show -n secret-file --vault-name testkeyvault | jq '.value | fromjson' > /usr/src/secret-file.json