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 store a string as a Secret, but how can I serialize a certificate in such way that I could retrieve it and deserialize as an 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
But when I tried to get it with GetKeyAsync method, I couldn't use it.
The original question asked how to retrieve the stored PFX as an
X509Certificate2
object. Using a Base64 process similar to that posted by Sumedh Barde above (which has the advantage of stripping the password), the following code will return a X509 object. In a real application, theKeyVaultClient
should be cached if you're retrieving multiple secrets, and the individual secrets should also be cached.Here's a PowerShell script for you. Replace the file path, password, vault name, secret name.
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.
Here is the script for uploading pfx certificate in python using azure cli
Getting the content of PFX file in python