将 Azure KeyVault Secret 转换为 RSACng 或 RSACryptoServiceProvide



编辑/添加:我在 Azure KeyVault 中生成了密钥(以及机密和证书)。 我没有上传或存储我创建的任何内容。 我的 KeyVault 中的所有内容都是 Azure 生成的。

在我的部分代码中,我使用 KeyVaultClient 检索密钥和机密,如下所示:

var azureClient = new KeyVaultClient(...);
var azureSecret = await azureClient.GetSecretAsync(...);
var privateKeyBytes = Convert.FromBase64String(azureSecret.Value);

这工作成功。 我甚至可以使用该值创建X509Certificate2。 本质上,这是我的流程:

  • 从 Azure 密钥保管库获取机密
  • SecretBundle值 (base64) 转换为字节
  • 从字节创建X509Certificate2
  • 从证书中GetRSAPublicKeyGetRSAPrivateKey
  • 使用RSACng成功加密和解密数据

但后来我问自己...为什么要传递密钥字节来构建证书...然后从证书中获取密钥并丢弃证书?

因此,经过一些研究,我找不到从 AzureSecretBundle直接到RSACryptoServiceProvider对象或RSACng对象的路径,即使通过CngKey

在其他代码中,我正在使用KeyVaultKeyResolver,并且想知道是否有一条路径通过类似的东西(虽然基于机密)来绕过 X509 转换。

作为一个附带问题,该SecretBundle.Value代表哪些数据? 我假设它是"X.509字节"之类的东西,因为我可以使用它来创建X509Cert2,并且我不能将其解构为私钥。

嗨,只是为了回答你的问题,我正在走那条路,但没有运气。我做了一些研究,发现你可以直接将应用程序/pkcs12内容写入pfx文件。

下面是一个帮助程序函数,可用于将 Azure 密钥保管库公钥/私钥(机密)转换为 pfx 文件。

public string GeneratePfxFile(string path, string certName, string rsaPublicKey, string privateKey)
{
var result = "";
try
{
var certPath = Path.Combine(path, certName);
if (File.Exists(certPath))
{
File.Delete(certPath);
}
var encodedText = Convert.FromBase64String(privateKey);

//  write the private key to file
using (FileStream sourceStream = new FileStream(certPath, FileMode.Append, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true))
{
sourceStream.Write(encodedText, 0, encodedText.Length);
}
var publicPart = Convert.FromBase64String(rsaPublicKey);
using (var stream = new FileStream(certPath, FileMode.Append, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: false))
{
stream.Write(publicPart, 0, publicPart.Length);
}
result = "Certificate File is created";
}
catch (Exception e)
{
result = $"Error: {e.Message}";
}
return result;
}

*流编写非常粗糙,但您可以提出优化的解决方案。

最新更新