0

I want to establish GRPC SslCredentials() using a certificate from my Windows Certificate Store under .Net 4.8. This link is quite similar but doesn't provide a working solution.

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. I wish the C# wrapper for GRPC would make this easy.

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());
            }
        }
    }
    ...
}
Hintz
  • 145
  • 2
  • 8

2 Answers2

0

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 ? 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();
}
G DeMasters
  • 61
  • 1
  • 5
0

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. One author pointed out that I could make it run on the latest Windows 10 OS but I can't be that limited.

Hintz
  • 145
  • 2
  • 8