Search code examples
c#azurecertificatex509certificate2azure-keyvault

How to serialize and deserialize a PFX certificate in Azure Key Vault?


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.


Solution

  • 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.