简体   繁体   English

GRPC C# SSL 客户端与 Windows 证书存储

[英]GRPC C# SSL Client with Windows Certificate Store

I want to establish GRPC SslCredentials() using a certificate from my Windows Certificate Store under.Net 4.8.我想使用来自.Net 4.8 下的 Windows 证书存储的证书建立 GRPC SslCredentials()。 This link is quite similar but doesn't provide a working solution.此链接非常相似,但没有提供有效的解决方案。

https://github.com/grpc/grpc/issues/8978 https://github.com/grpc/grpc/issues/8978

I use code similar to the following.我使用类似于以下的代码。 The ExportToPEM() is a home-grown attempt to convert the certificate to PEM format, but it doesn't work. ExportToPEM() 是一种将证书转换为 PEM 格式的本土尝试,但它不起作用。 I wish the C# wrapper for GRPC would make this easy.我希望 GRPC 的 C# 包装器能让这一切变得简单。

var cred = new SslCredentials(GetCertificate());
Channel = new Channel("127.0.0.1", BINDING_PORT, cred);

            
private static string GetCertificate()
{
    var storex = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
    storex.Open(OpenFlags.ReadOnly);
    var certificatesx = storex.Certificates.Find(X509FindType.FindBySubjectName, CERTIFICATE_SUBJECTNAME, true);
    if (certificatesx.Count > 0)
    {
        foreach (X509Certificate2 cert in certificatesx)
        {
            if (!string.IsNullOrWhiteSpace(cert.FriendlyName) && cert.FriendlyName == ROOT_CERTIFICATE_FRIENDLYNAME)
            {
               return ExportToPEM(cert.GetRSAPrivateKey());
            }
        }
    }
    ...
}

Have you tried the code from the answer to Grpc.Net client fails to connect to server with SSL given by https://stackoverflow.com/users/727250/rene-r ?您是否尝试过 Grpc.Net 客户端无法使用https://stackoverflow.com/users/727250/rene-r给出的 SSL 连接到服务器的代码 It gives the cert, you are pulling the key in your code, but easy substitution.它提供了证书,您在代码中提取密钥,但很容易替换。

/// <summary>
/// Export a certificate to a PEM format string
/// </summary>
/// <param name="cert">The certificate to export</param>
/// <returns>A PEM encoded string</returns>
private static string ExportToPem(X509Certificate cert)
{
    StringBuilder builder = new StringBuilder();
    builder.AppendLine("-----BEGIN CERTIFICATE-----");
    builder.AppendLine(Convert.ToBase64String(cert.Export(X509ContentType.Cert),Base64FormattingOptions.InsertLineBreaks));
    builder.AppendLine("-----END CERTIFICATE-----");

    return builder.ToString();
}

I found that the pre-release of Grpc.Net.Core handled the certificate automatically and provides.Net standard 2.0 support but I've abandon the GRPC architecture because I could not make it work on the necessary.Net 4.8 client and OS mix.我发现 Grpc.Net.Core 的预发布版本会自动处理证书并提供 .Net 标准 2.0 支持,但我放弃了 GRPC 架构,因为我无法使其在必要的.Net 4.8 客户端和操作系统组合上工作。 One author pointed out that I could make it run on the latest Windows 10 OS but I can't be that limited.一位作者指出,我可以让它在最新的 Windows 10 操作系统上运行,但我不能受限制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM