Dan*_*ary 6 .net c# azure x509 azure-keyvault
我使用Azure Key Vault来保护我们的密钥和机密,但我不确定如何使用我使用.net SDK检索的KeyBundle.如何创建X509Certificate2对象?
joh*_*hni 16
在KeyVault中导入/创建证书时,将创建3个实体:
证书 - 包含有关证书的所有相关详细信息,包括其公共部分(即公钥,有效期,指纹等)
密钥 - 包含base64中的私钥(证书的私有部分)
您可以X509Certificate2使用Certificate对象或Secret对象创建对象.
如果您想要X509Certificate2包含私钥,那么当然您需要获取Secret实体的值并执行以下操作:
SecretBundle certificatePrivateKeySecretBundle =
await keyVaultClient.GetSecretAsync(certificateIdentifierSecretPart);
byte[] privateKeyBytes = Convert.FromBase64String(certificatePrivateKeySecretBundle.Value);
X509Certificate2 certificateWithPrivateKey = new X509Certificate2(privateKeyBytes, (string) null, X509KeyStorageFlags.MachineKeySet);
Run Code Online (Sandbox Code Playgroud)
该certificateIdentifierSecretPart等于证书的秘密部分路径:
https://<vault name>.vaults.azure.net/secrets/<certificate name>
注意/ secrets / path.
2020 年 11 月更新:
在当前版本的 Azure Key Vault 中,证书 是一流的概念,而不是一种机密。
如果您的 Key Vault 实例已经有一个带有可导出私钥的证书,您X509Certificate2将按如下方式获取它并合成一个:
使用DefaultAzureCredential创建所需的客户端
var certClient = new CertificateClient(new Uri("https://yourKeyVault.vault.azure.net/"), new DefaultAzureCredential());
var secretClient = new SecretClient(new Uri("https://yourKeyVault.vault.azure.net/"), new DefaultAzureCredential());
Run Code Online (Sandbox Code Playgroud)
获取证书,其中包含指向私钥秘密的链接。
注意:Key Vault Secrets 库的最新 (4.2.0 beta) 版本包括一个名为KeyVaultSecretIdentifier的帮助程序类,它会为您进行解析。
Response<KeyVaultCertificateWithPolicy> certResponse = await certClient.GetCertificateAsync("testCert");
// If using client version 4.2.0 or later
KeyVaultSecretIdentifier identifier = new KeyVaultSecretIdentifier(certResponse.Value.SecretId);
// Else, Get the secretId and parse out the parts needed to fetch the secret.
Uri secretId = certResponse.Value.SecretId;
var segments = secretId.Segments;
string secretName = segments[2].Trim('/');
string version = segments[3].TrimEnd('/');
Run Code Online (Sandbox Code Playgroud)
获取证书的秘密并使用它来构建一个新的X509Certificate2.
// If using client version 4.2.0 or later
Response<KeyVaultSecret> secretResponse = await secretClient.GetSecretAsync(identifier.Name, identifier.Version);
// else
Response<KeyVaultSecret> secretResponse = await secretClient.GetSecretAsync(secretName, version);
KeyVaultSecret secret = secretResponse.Value;
byte[] privateKeyBytes = Convert.FromBase64String(secret.Value);
var cert = new X509Certificate2(privateKeyBytes);
Run Code Online (Sandbox Code Playgroud)
有关最新的 Key Vault 证书和 Secret 客户端的更多信息,请在此处查看它们各自的 README 文档:
Azure.Security.KeyVault.Certificates(从旧版本迁移指南)
Azure.Security.KeyVault.Secrets(从旧版本迁移指南)
您不能将 KeyBundle 结果用作 X509Certificate2 对象,因为它仅表示此处密钥对的公钥部分(无颁发者)。请参阅KeyVaultClientExtensions中的方法,了解使用此 KeyBundle 对象加密数据、验证签名等的功能。
| 归档时间: |
|
| 查看次数: |
3406 次 |
| 最近记录: |