azure 无法获取X509 Certificate 2- p12证书的新示例

8i9zcol2  于 2023-06-24  发布在  其他
关注(0)|答案(1)|浏览(94)

尝试从Azure Blob Storage下载p12证书时,在Azure App Service中生成正确的X509Certificate2示例时遇到问题。这段代码可以在localhost上运行:

public async Task<Option<X509Certificate2, ApplicationException>> GetCertificate(string fileName, string keyCert)
{
    try
    {
        string connString = $"XXX";
        string containerName = $"certificates";

        var stream = await _storageService.DownloadBlob(connString, containerName, fileName);

        byte[] certData = stream.ToArray();

        var certificate = new X509Certificate2(certData, keyCert, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.EphemeralKeySet);

        if (certificate is null)
            return Option.None<X509Certificate2, ApplicationException>(new ApplicationException("Error while capturing the certificate."));

        return Option.Some<X509Certificate2, ApplicationException>(certificate);
    }
    catch (Exception ex)
    {
        return Option.None<X509Certificate2, ApplicationException>(new ApplicationException(ex.HResult.ToString() + " " + ex.StackTrace + " " + ex.TargetSite + " " + ex.Message));
    }
}

但是,在Azure应用服务中,我遇到了以下异常:
Microsoft.Win32.SafeHandles.SafeCertContextHandle FilterPFXStore(System.ReadOnlySpan 1[System.Byte],Microsoft.Win32.SafeHandles.SafePasswordHandle,PfxCertStoreFlags)发生内部错误。`

3ks5zfa0

3ks5zfa01#

当证书未正确加载时,可能会出现此错误。Microsoft.Win32.SafeHandles.SafeCertContextHandle FilterPFXStore(System.ReadOnlySpan1[System.Byte], Microsoft.Win32.SafeHandles.SafePasswordHandle, PfxCertStoreFlags) An internal error occurred.

  • 通过在文本编辑器中打开证书并检查其格式是否正确来检查证书的格式。

此外,这可能是由于没有从正确的位置加载证书。检查从正确位置加载的证书,并查看证书的路径。
使用Azure Key Vault在Azure应用服务中存储和检索证书。

var cert_Client = new CertificateClient(new Uri("https://<your-key-vault-name>.vault.azure.net/"), new DefaultAzureCredential());

var certificate = await cert_Client.GetCertificateAsync("<your-certificate-name>");

var x509Certificate2 = new X509Certificate2(certificate.Value.Cer);

用C#编写代码从Azure容器下载文件。

string conStr = "Connection_String";
string cntr = "tstcntr";
List<string> Cert_list = new List<string>();
Cert_list.Add("mycert1144.pfx");
Cert_list.Add("mycert1144.cer");

string path = "C:\\Tools\\cert";

foreach (string blb in Cert_list)
{
    BlobServiceClient blbSvcClnt = new BlobServiceClient(conStr);
    BlobContainerClient cntrClnt = blbSvcClnt.GetBlobContainerClient(cntr);
    BlobClient blbClnt = cntrClnt.GetBlobClient(blb);
    BlobDownloadInfo download = await blbClnt.DownloadAsync();

    using (FileStream fileStream = File.OpenWrite(path))
    {
        await download.Content.CopyToAsync(fileStream);
        fileStream.Close();
    }
}
Console.WriteLine("Certificate downloaded successfully!");

集装箱证书。

下载的文件。

有关详细信息,请参阅X509Certificate2构造程序。

相关问题