zde*_*man 13 c# certificate azure x509certificate2 azure-keyvault
我有一堆字符串和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
Run Code Online (Sandbox Code Playgroud)
但是当我试图用GetKeyAsync方法获取它时,我无法使用它.
Sum*_*rde 11
这是适合您的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
Run Code Online (Sandbox Code Playgroud)
这是一个常见的问题,因此我们将对此进行改进并作为帮助者发布.
上面的脚本剥离了密码,因为密码保护PFX没有价值,然后将密码存储在旁边.
原始问题询问如何将存储的PFX检索为X509Certificate2
对象.使用类似于Sumedh Barde上面发布的Base64进程(具有剥离密码的优点),以下代码将返回X509对象.在实际应用程序中,KeyVaultClient
如果您正在检索多个机密,则应该缓存它,并且还应该缓存单个机密.
public static async Task<X509Certificate2> 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 client.GetSecretAsync($"{baseUri}{secretName}").ConfigureAwait(false);
string pfx = secretBundle.Value;
var bytes = Convert.FromBase64String(pfx);
var coll = new X509Certificate2Collection();
coll.Import(bytes, "certificatePassword", X509KeyStorageFlags.Exportable);
return coll[0];
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
12315 次 |
最近记录: |