如何在Azure Key Vault中序列化和反序列化PFX证书?

我有一堆字符串和pfx证书,我想存储在Azure Key保险库中,只允许用户/应用程序获取它们。 将字符串存储为Secret并不难,但是如何以可以检索它的方式序列化证书并在C#中反序列化为X509Certificate2对象?

我试着将它存储为钥匙。 这是Azure powershell代码

$securepfxpwd = ConvertTo-SecureString -String 'superSecurePassword' -AsPlainText -Force $key = Add-AzureKeyVaultKey -VaultName 'UltraVault' -Name 'MyCertificate' -KeyFilePath 'D:\Certificates\BlaBla.pfx' -KeyFilePassword $securepfxpwd 

但是当我试图用GetKeyAsync方法获取它时,我无法使用它。

这是适合您的PowerShell脚本。 替换文件路径,密码,保管库名称,密码名称。

 $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 

这是一个常见的问题,因此我们将对此进行改进并作为帮助者发布。

上面的脚本剥离了密码,因为密码保护PFX没有价值,然后将密码存储在旁边。

原始问题询问如何将存储的PFX检索为X509Certificate2对象。 使用类似于Sumedh Barde上面发布的Base64进程(具有剥离密码的优点),以下代码将返回X509对象。 在实际应用程序中,如果您正在检索多个机密,则应缓存KeyVaultClient ,并且还应缓存单个机密。

 public static async Task GetSecretCertificateAsync(string secretName) { string baseUri = @"https://xxxxxxxx.vault.azure.net/secrets/"; var provider = new AzureServiceTokenProvider(); var client = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(provider.KeyVaultTokenCallback)); var secretBundle = await KeyVaultClient.GetSecretAsync($"{baseUri}{secretName}").ConfigureAwait(false); string pfx = secretBundle.Value; var bytes = Convert.FromBase64String(pfx); var coll = new X509Certificate2Collection(); coll.Import(bytes, null, X509KeyStorageFlags.Exportable); return coll[0]; } 

这是使用azure cli在python中上传pfx证书的脚本

 azure keyvault secret set --vault-name  --secret-name  --value  

在python中获取PFX文件的内容

 fh = open(self.getPfxFilePath(), 'rb') try: ba = bytearray(fh.read()) cert_base64_str = base64.b64encode(ba) password = self.getPassword() json_blob = { 'data': cert_base64_str, 'dataType': 'pfx', 'password': password } blob_data= json.dumps(json_blob) content_bytes= bytearray(blob_data) content = base64.b64encode(content_bytes) return content finally: fh.close fh.close()