I have a bunch of strings and pfx certificates, which I want to store in Azure Key vault, where only allowed users/apps will be able to get them. It is not hard to do it with the strings (just create a secret), but how can I store a certificate in such way that I could retrieve it and initialize it as a X509Certificate2 object in C#?
I tried to store it as a key. Here is the Azure powershell code
$securepfxpwd = ConvertTo-SecureString -String 'superSecurePassword' -AsPlainText -Force
$key = Add-AzureKeyVaultKey -VaultName 'UltraVault' -Name 'MyCertificate' -KeyFilePath 'D:\Certificates\BlaBla.pfx' -KeyFilePassword $securepfxpwd
Here's a PowerShell script for you. Replace the file path, password, vault name, secret name.
$pfxFilePath = 'C:\mycert.pfx' $pwd = '123' $flag = [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable $collection = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection $collection.Import($pfxFilePath, $pwd, $flag) $pkcs12ContentType = [System.Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12 $clearBytes = $collection.Export($pkcs12ContentType) $fileContentEncoded = [System.Convert]::ToBase64String($clearBytes) $secret = ConvertTo-SecureString -String $fileContentEncoded -AsPlainText –Force $secretContentType = 'application/x-pkcs12' Set-AzureKeyVaultSecret -VaultName 'myVaultName' -Name 'mySecretName' -SecretValue $Secret -ContentType $secretContentType
This is a common question, so we are going to polish this up and release as a helper.
The script above strips the password because there's no value in having a password protected PFX and then storing the password next to it.